Skip to content

Instantly share code, notes, and snippets.

@jackrusher
Last active September 25, 2017 18:51
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jackrusher/4360119 to your computer and use it in GitHub Desktop.
A very simple implementation of Markov chaining in Clojure.
(defn model-from-sequence
"Returns a transition matrix of 'depth' from 'sequence'"
[depth sequence]
(loop [accum {} chunks (partition (inc depth) 1 (seq sequence))]
(if (seq? chunks)
(let [chunk (first chunks)
prefix (drop-last chunk)
suffix (last chunk)]
(recur (assoc accum prefix (conj (get accum prefix []) suffix)) (next chunks)))
accum)))
(defn chain
"Returns a lazy Markov chain starting with 'current' using matrix 'trans'"
[current trans]
(if-let [transitions (trans current)]
(cons (first current)
(lazy-seq (chain (concat (rest current) [(rand-nth transitions)]) trans)))
current))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment