3

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

2 Answers 2

10

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Wonderfull, exactly what I was look for. It was in plain sight the whole time and I still overlooked it.
1

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

1 Comment

Thanks, this also works but the solution with nth above is a bit more elegant. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.