Start with an element, apply function f repeatedly to each new element while adding them to a vector

Viewed 87

In Clojure, is there some general purpose function (similar to higher order functions map, filter, reduce, where one starts, say, with a vector with one element, applies function f to the element, add the element to the vector, and apply the function to the new element, and continue as such until some condition is met.

Example: I have vector [1], function double, and the function I am after, call it f, and, something like:

(take-while some-pred (f double 1))

which produces: [1 2 4 8 16 32 . . .]

1 Answers

i guess you're talking about iterate:

(take-while #(< % 1000) (iterate #(* 2 %) 1))
;;=> (1 2 4 8 16 32 64 128 256 512)

if you need vector, you can also use transducer:

(into [] (take-while #(< % 1000)) (iterate #(* 2 %) 1))
;; [1 2 4 8 16 32 64 128 256 512]
Related