Reputation: 595
Given n, x, f: I want output of the form:
[x, f(x), f(f(x)), f(f(f(x))), ..., f^{n-1}(x)]
This can be done via reductions
(reductions
(fn [state _] (f state))
state
(range n))
Is there a primitive that provides a shorter solution?
Upvotes: 1
Views: 381
Reputation: 2425
What you want is clojure.core/iterate, which provides f -> x -> [x, f(x), f^2(x), f^3(x), ...]
and clojure.core/take which provides a way to slice the first n
elements off of a sequence. take
is lazy, as is iterate
so there are no guarantees about side-effects.
Upvotes: 8