Skip to content

Instantly share code, notes, and snippets.

@paulsmith
Created November 9, 2009 20:56
Show Gist options
  • Save paulsmith/230273 to your computer and use it in GitHub Desktop.
Save paulsmith/230273 to your computer and use it in GitHub Desktop.
Another toy Markov chain generator, this time in Clojure
(def state (ref {}))
(def nonword "\n")
(defn get-words
[]
(loop [words []]
(let [line (read-line)]
(if (nil? line)
words
(recur (into words (remove empty? (.split #"\s+" line))))))))
(defn build
[]
(dosync
(loop [words (get-words)
prefix [nonword nonword]]
(let [suffixes (get @state prefix [])
word (first words)]
(if (nil? word)
(alter state conj {prefix (conj suffixes nonword)})
(do
(alter state conj {prefix (conj suffixes word)})
(recur (rest words) (vector (prefix 1) word))))))))
(defn generate
[]
(loop [prefix [nonword nonword]
n 100]
(if (not (zero? n))
(let [suffixes (get @state prefix)
word (suffixes (rand-int (count suffixes)))]
(if (not (= word nonword))
(do
(print word "")
(recur [(prefix 1) word] (- n 1))))))))
(build)
(generate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment