Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a function n times on a starting value

Tags:

clojure

Basically I want to apply f on x for n times and I am only interested in the result. Is there any better way than (nth (iterate f x) n)?

like image 487
Hengrui Jiang Avatar asked Oct 09 '17 21:10

Hengrui Jiang


1 Answers

as the commenters said, your solution is already ok. another option is to use comp, like this maybe:

user> (defn n-times [n f]
        (apply comp (repeat n f)))
#'user/n-times

user> ((n-times 10 inc) 1)
;;=> 11

Still I can't really say if it is better then yours in any aspect. Maybe a bit more functional[ish]

like image 102
leetwinski Avatar answered Oct 20 '22 23:10

leetwinski