eav db
eav db

Reputation: 595

clojure: reductions: applying function n times, keeping intermediate results

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?

Upvotes: 1

Views: 381

Answers (1)

arrdem
arrdem

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

Related Questions