user1782011
user1782011

Reputation: 915

repeat function n times in recursion on input (without loop recur)

I know I can solve my problem with loop and recur but it seems such a simple (common?) operation that I was wondering if there was no single function in clojure or less cluttered approach then loop/ recur to solve this. I searched for it but was not able to find something.

The function I was looking for is the following.

(the-function n input some-function)

where n is the number of time to recursivle call some-function on the input.

A simple example would be:

(the-function 3 1 (fn [x] (+ x 1)))
=> 4 

Is ther anything like that in Clojure?

Best regards

Upvotes: 3

Views: 1207

Answers (2)

tangrammer
tangrammer

Reputation: 3061

Try this:

(defn your-iterate-fn [times init-param the-fn] 
    (last (take (inc times) (iterate the-fn init-param))))
(your-iterate-fn 3 1 (fn [x] (+ x 1)))
==> 4

Upvotes: 1

Chuck
Chuck

Reputation: 237110

What you want is basically iterate. It will generate an infinite sequence of repeated applications of a function to a seed input. So to replicate the behavior you describe here, you would write:

(nth (iterate some-function input) n)

Upvotes: 10

Related Questions