Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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

like image 359
user1782011 Avatar asked Jun 27 '26 21:06

user1782011


2 Answers

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)
like image 72
Chuck Avatar answered Jun 29 '26 12:06

Chuck


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
like image 41
tangrammer Avatar answered Jun 29 '26 13:06

tangrammer