Skip to content

Instantly share code, notes, and snippets.

Created November 7, 2013 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/7363231 to your computer and use it in GitHub Desktop.
Save anonymous/7363231 to your computer and use it in GitHub Desktop.
(defn smap [state func coll]
(loop [state state
ans '()
coll coll]
(if (empty? coll)
(reverse ans)
(let [[ns v] (func state (first coll))]
(recur ns
(cons v ans)
(rest coll))))))
@timmc
Copy link

timmc commented Nov 7, 2013

(defn smap
  "Given a function of [state in-val -> [state out-val]], an initial
  state, and a collection of input values, yield the output values as
  the function is walked over the inputs with state kept up to date."
  [f state xs]
  (when (seq xs)
    (let [[new-state out] (f state (first xs))]
      (cons out (lazy-seq (smap f new-state (next xs)))))))

=> (smap (fn [s i] [(inc s) (+ s i)]) 0 [10 100 1000 10000])
(10 101 1002 10003)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment