Skip to content

Instantly share code, notes, and snippets.

@llowder
Created December 12, 2014 19:21
Show Gist options
  • Save llowder/01dd365089b7b2f5cb80 to your computer and use it in GitHub Desktop.
Save llowder/01dd365089b7b2f5cb80 to your computer and use it in GitHub Desktop.
(ns callofmylittlepuppet.core
(:gen-class))
(defn transform
[words]
(->> words
(partition 4 1)
(reduce (fn [acc [w next-w]]
(update-in acc
[w next-w]
(fnil inc 0)))
{})))
(defn markers [line]
(concat [:start]
(clojure.string/split line #"\s+")
[:end]))
(defn lazy-lines [file]
(letfn [(helper [rdr]
(lazy-seq
(if-let [line (.readLine rdr)]
(concat (markers line) (helper rdr))
(do (.close rdr) nil))))]
(helper (clojure.java.io/reader file))))
(defn wrand
[slices]
(let [total (reduce + slices)
r (rand total)]
(loop [i 0 sum 0]
(if (< r (+ (slices i) sum))
i
(recur (inc i) (+ (slices i) sum))))))
(defn generate-sentence [data]
(loop [ws ( data :start)
acc []]
(let [v (vec (vals ws))
i (wrand v)
w (nth (keys ws) i)
nws (data w)]
(if (= :end w)
(clojure.string/join " " acc)
(recur nws (concat acc [w]))))))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(let [markov (transform (lazy-lines (first args)))]
(loop [x 0]
(when (< x 5000)
(println (concat [x] [": "] [ (generate-sentence markov)]))
(recur (+ x 1))
)
)
)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment