iterate

6 megtekintés
Ugrás az első olvasatlan üzenetre

notallama

olvasatlan,
2008. nov. 13. 2:25:582008. 11. 13.
– Clojure
i put this at the end of my boot.clj for added fun:

(defn iterate
"returns a lazy seq of arg1, arg2 ... argn, (f arg1 ... argn), (f
arg2 ... argn (f arg1 ... argn)), etc."
[f & [x & rest :as all]]
(lazy-cons x (apply iterate f (concat rest [(apply f all)]))))


user=> (take 10 (iterate + 1 1))
(1 1 2 3 5 8 13 21 34 55)

user=> (take 4 (iterate #(* % %) 2))
(2 4 16 256)

is this good as a contrib? is there a better way to implement this?
also, this language is delightful.

Parth Malwankar

olvasatlan,
2008. nov. 13. 3:36:202008. 11. 13.
– Clojure
There is already an "iterate" in Clojure.
Your implementation much have shadowed it.

user=> (doc iterate)
-------------------------
clojure/iterate
([f x])
Returns a lazy seq of x, (f x), (f (f x)) etc. f must be free of
side-effects
nil
user=> (iterate #(+ 1 %) 1)
(1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
27 28 29 3
0 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 ...)

But it doesn't take multiple arguments like your
implementation. Thats a nice enhancement.

Parth
Válasz mindenkinek
Válasz a szerzőnek
Továbbítás
0 új üzenet