Markov chain text generator: Difference between revisions

+Racket
m (Removed dead link)
(+Racket)
Line 1,190:
the Land of Oz, said Dorothy, and I am thankful I am made of straw and
cannot be easily damaged.</pre>
 
=={{header|Racket}}==
<lang racket>#lang racket
 
(define (pick xs) (list-ref xs (random (length xs))))
 
(define (markov path N limit)
(define xs (string-split (file->string path)))
(define database (make-hash))
(let loop ([xs xs])
(define-values (prefix suffix*) (split-at xs N))
(match suffix*
[(cons suffix _)
(hash-update! database prefix (curry cons suffix) '())
(loop (rest xs))]
[_ (hash-update! database prefix (curry cons "") '())]))
 
(define prefix (car (pick (hash->list database))))
(let loop ([prefix prefix] [out (reverse prefix)] [i 0])
(cond
[(= i limit) (string-join (reverse out) " ")]
[(hash-ref database prefix #f)
=> (λ (suffixes)
(define suffix (pick suffixes))
(loop (append (rest prefix) (list suffix))
(cons suffix out)
(add1 i)))])))
 
(markov "alice_oz.txt" 3 300)</lang>
 
{{out}}
<pre>
"The Scarecrow, who was never tired, stood up in another corner and waited patiently until it chose to speak again. In a minute I shall melt away. I'm very sorry, indeed, said Dorothy, who was truly sorry for him. If you will help me sew the silk together, we will begin to work on our balloon. So Dorothy took a needle and thread, and as fast as Oz cut the strips of silk into proper shape the girl sewed them neatly together. First there was a body to cut it off from: that he had never had to do such a thing before, and he wasn't going to begin again, it was very like having a game of croquet she was playing against herself, for this curious child was very fond of pretending to be two people. 'But it's no use going back to yesterday, because I was a young man when the balloon brought me here, and I am only a little girl. But you were strong enough to kill the Wicked Witch of the East, and promised her two sheep and a cow if she would prevent the marriage. Thereupon the Wicked Witch and setting them free from bondage. So she chose a number of the Winkies she will find you, and make you all her slaves. Perhaps not, said the Scarecrow, in a grieved tone; you're a humbug. Exactly so! declared the little man, rubbing his hands together as if it were not one of the shoes she owned half the power of the Golden Cap; but if she could only get back to Kansas. The Silver Shoes, said the Good Witch, have wonderful powers. And one of the eyes slowly wink at her. She thought she must have a basket to ride in, he said. So he sent the"
</pre>
 
=={{header|REXX}}==
Anonymous user