首页 > 解决方案 > Trying to understand clojure Fibonacci recursion

问题描述

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?

标签: recursionclojure

解决方案


就是conj, for lists的行为。conj并不总是添加到最后:

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

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

添加元素的位置取决于集合的类型。由于添加到列表的末尾很昂贵,因此conj添加到前面。这是相同的操作(添加到列表),但针对正在使用的集合进行了优化。


推荐阅读