I'm studying the Clojure Koans:
https://github.com/functional-koans/clojure-koans/blob/master/src/koans/10_lazy_sequences.clj
I am stuck on this one:
"Iteration can be used for repetition"
(= (repeat 100 :foo)
(take 100 (iterate ___ :foo)))
I don't know the exact builtin function to fill in the _ blanks with, so I tried writing my own. I wrote it as a separate function as a test.
I intend this one to be: if x is a seq, then just repeat its first element. Otherwise, make it a seq.
(def f (fn [x] (if (seq? x) (cons (first x) x) (cons x '()))))
When I run it explicitly, it looks fine:
user=> (f :abc)
(:abc)
user=> (f (f :abc))
(:abc :abc)
user=> (f (f (f :abc)))
(:abc :abc :abc)
But using iterate
adds an extra parenthesis:
user=> (take 1 (iterate f :abc))(:abc)
user=> (take 2 (iterate f :abc))
(:abc (:abc))
user=> (take 3 (iterate f :abc))
(:abc (:abc) (:abc :abc))
What causes this?
is that iterate is (computing|mathematics) to perform or repeat an action on each item in a set while repeat is (intransitive) to do or say again (and again). is that iterate is (mathematics) a function that iterates while repeat is an iteration; a repetition. is (obsolete) said or done again; repeated.
In mathematics, an iterated function is a function which is composed with itself, possibly ad infinitum, in a process called iteration. (archaic) To utter or do a second time or many times; to repeat. Nor Eve to iterate / Her former trespass feared.
Iteration: Infinite iteration due to mistake in iterator assignment or increment, or in the terminating condition, will lead to infinite loops, which may or may not lead to system errors, but will surely stop program execution any further. Function calls itself. A set of instructions repeatedly executed.
If one does one thing repeatedly, it ’ s iteration. When one takes the result of an operation and applies the same operation to it wherever it is, that ’ s recursion. It ’ s slightly confusing, because simple cases of recursion are just iteration.
(fn [x] x)
solves this particular koan
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With