In the code I'm writing, I seem to run into a certain pattern a lot.
Often enough anyway that I thought there must be a different way of
doing it - otherwise there would be a macro or function for it.
The gist is that a function is applied to each member of a sequence,
like map, except that the function also takes a changing state. The
change to the state is described by a second function.
Here's a function describing the pattern.
(defn stateful-map [fn-item fn-state start-state start-items]
(loop [state start-state
items start-items
result nil]
(if (nil? items)
(reverse result)
(let [item (first items)
new-item (fn-item state item)
new-state (fn-state state item)]
(recur new-state (rest items) (cons new-item result))))))
So the question is, is there a better way of doing this?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---