Created
November 9, 2009 20:56
-
-
Save paulsmith/230273 to your computer and use it in GitHub Desktop.
Another toy Markov chain generator, this time in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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