I was going through 4clojure (highly recommended!) and doing the Fibonacci
exercise. It occurred to me that the iterate function could be generalized
in a reasonable way, so that the next value is generated by applying the
function to the last N items so far, where N is the number of initial
arguments beyond the function. Thus:
(generate inc 1)
works just like iterate, while
(generate + 1 1)
generates the Fibonacci sequence.
Here's the code:
(defn generate
[f & more]
(letfn [(recurse
[coll args]
(let [next-val (apply f args)]
(lazy-cat coll (recurse [next-val] (conj (butlast args)
next-val)))))]
(recurse more (reverse more))))
Code is also on Github <https://github.com/nchurch/generate>.
I see this as part of a larger class of generalized sequence functions: for
instance, extra arguments in a function given to *reduce* could refer to N
arguments back in the sequence (might be useful, for instance, in smoothing a
sequence of values using an average).
Questions: is there an existing home for this kind of functionality? And could
the above code be improved? (I just used the definition of *iterate* as a
starting point.)
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
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
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.