Skip to content

Instantly share code, notes, and snippets.

@chrisvest
Created August 26, 2010 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisvest/552253 to your computer and use it in GitHub Desktop.
Save chrisvest/552253 to your computer and use it in GitHub Desktop.
; Generate random output from input seed-text, using a Markov chain.
MAXGEN = 10000
NONWORD = "\n"
HEAD = NONWORD, NONWORD
prefix := HEAD
statetab = HashMap with-factory: (= Vector)
to start
"The program entry point. Procedure names should be verbs, hence 'main' is out."
build-chain-from stdin
add NONWORD ; to mark the end of the Markov chain
generate-markov-text MAXGEN
to build-chain-from input
"Build the Markov chain from the given input stream."
for word in input words
add word
to add word
"Add a suffix word to the Markov for the current prefix."
statetab prefix push word
prefix pop push word
to generate n-words
"Generate at most n-words of output text from the Markov chain,
or until we hit a NONWORD."
prefix clear add-all HEAD
for i in 0 .. n-words
word = statetab prefix random-element
if word is NONWORD
return
stdout println word
prefix pop push word
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment