Clojure递归链接列表 [英] clojure recursion conj a list
问题描述
((fn foo [x] (when (> x 0) (conj (foo (dec x)) x))) 5)
对于此代码,结果为[5 4 3 2 1]为什么不是[1,2,3,4,5]?我看到我们从带有值的递归foo调用的结果中进行配置.因为我认为应该是1 2 3 4 5?需要帮助来了解这一点.谢谢.
For this code, the result is [5 4 3 2 1] Why isn't is [1,2,3,4,5]? I see we do conf from result of recursive foo call with a value. For I thought it should be 1 2 3 4 5? Need help to understand this. Thanks.
推荐答案
来自 conj
的文档:
clojure.core/conj
([coll x] [coll x& xs])
conj [oin].返回带有xs
的新集合'添加'.(conn nil item)返回(item).添加"可能
发生在不同的地方",具体取决于具体的类型.
clojure.core/conj
([coll x] [coll x & xs])
conj[oin]. Returns a new collection with the xs
'added'. (conj nil item) returns (item). The 'addition' may
happen at different 'places' depending on the concrete type.
函数的终止条件产生 nil
,因为测试是一个when.因此,最深层的conj调用将是:
The termination condition of your function yields nil
, because the test is a when. So the deepest conj call will be:
(conj nil 1)
(1) <-- a list
下一个:
(conj (conj nil 1) 2)
(2 1)
所以您的结果将以降序排列,因为conj附加在列表的最前面.如果您希望按升序排列,请从一个空向量开始,如下所示:
So your result will be in decreasing order because conj appends at the front for lists. If you want it in increasing order, start with an empty vector like this:
((fn foo [x] (if (> x 0) (conj (foo (dec x)) x) [])) 5)
[1 2 3 4 5]
这篇关于Clojure递归链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!