public
Last active

A very simple implementation of Markov chaining in Clojure.

  • Download Gist
SimpleMarkovChain.clj
Clojure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
(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))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.