Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between iterate and repeatedly applying a function

Tags:

clojure

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?
like image 455
mparaz Avatar asked Sep 08 '12 09:09

mparaz


People also ask

What is the difference between iterate and repeat?

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.

What does it mean to iterate a function?

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.

What is infinite iteration in programming?

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.

What is the difference between iteration and recursion?

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.


1 Answers

(fn [x] x)

solves this particular koan

like image 156
Pedro Howat Avatar answered Sep 21 '22 14:09

Pedro Howat