0

I am trying to understand the below program to find the Fibonacci series using recursion in Clojure.

(defn fib
[x] 
(loop [i '(1 0)]
    (println i)
    (if (= x (count i))
        (reverse i)
        (recur 
          (conj i (apply + (take 2 i))))))) // This line is not clear

For ex for a call fib(4) I get the below output,

(1 0)
(1 1 0)
(2 1 1 0)
(0 1 1 2)

Which as per my inference the conj seems to add the value of (apply + (take 2 i)) to the start of the i. But that is not the behaviour of conj. Can someone help me understand how exactly this works?

2 Answers 2

2

That is the behavior of conj, for lists. conj doesn't always add to the end:

(conj '(1) 2) ; '(2 1)

(conj [1] 2) ; [1 2]

The placement of the added element depends on the type of the collection. Since adding to the end of a list is expensive, conj adds to to front instead. It's the same operation (adding to a list), but optimized for the collection being used.

Sign up to request clarification or add additional context in comments.

Comments

1

Per Clojure documentation:

The 'addition' may happen at different 'places' depending on the concrete type.

Appending to list happens to beginning of list, appending to vector happens to the end...

See more examples at https://clojuredocs.org/clojure.core/conj

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.