recursion - 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?
解决方案
这就是conj
, for lists的行为。conj
并不总是添加到最后:
(conj '(1) 2) ; '(2 1)
(conj [1] 2) ; [1 2]
添加元素的位置取决于集合的类型。由于添加到列表的末尾很昂贵,因此conj
添加到前面。这是相同的操作(添加到列表),但针对正在使用的集合进行了优化。
推荐阅读
- node.js - 如何解决您的函数被杀死,因为它在我的 Firebase 模拟器中引发了未处理的错误?
- python - 迁移后数据库中的表未在数据库中创建并在 Django 中迁移
- angular - 在创建 get Observable Angular 后添加 http 标头
- javascript - 获取要在 if 语句中使用的返回值
- asp.net-mvc - 提交编辑自动返回编辑页面?
- typescript - 类类型为具有构造函数属性的对象......没有自定义构造函数签名?
- json - Jsr223 断言在 jmeter 中的 json 响应失败
- css - 根据 ReactJs 中的事件改变状态
- oracle - 位图索引全扫描是否在 Oracle 中执行排序?
- vim - 如何让 vim 正确呈现阿拉伯文本?