1

Problem Statement

Given n, x, f: I want output of the form:

[x, f(x), f(f(x)), f(f(f(x))), ..., f^{n-1}(x)] 

Existing solution

This can be done via reductions

(reductions (fn [state _] (f state)) state (range n)) 

Question

Is there a primitive that provides a shorter solution?

1
  • 8
    Wouldn't iterate do this? For your specific requirement, I think it would be (take n (iterate f x)). Commented Nov 16, 2016 at 4:24

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Though both are lazy, neither iterate nor take are subject to chunking, so far as I can see from the source code. Nor can I see how you could implement iterate to take advantage of parallelism.
thought there would be a builtin for this. thanks!
FYI, I edited your answer to remove the discourse on chunking and laziness, because (1) it's not really related to the question as asked, and (2) I believe it's erroneous ((a) iterate isn't implemented as a chunked sequence, and (b) for arbitrary f, how would you compute f^n(x) without first computing f^(n-1)(x)?). If you feel otherwise, feel free to revert.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.