在clojure中递归

mur*_*a52 2 clojure

我正在尝试使这个示例程序工作

(defn foo
  ([x] (foo x []))
  ([x current]
     (when (> x 0)
       (recur (dec x) (conj current x)))))
Run Code Online (Sandbox Code Playgroud)

当我调用这个函数(foo 5)时,我应该得到[1 2 3 4 5],但它只返回nil.我究竟做错了什么?

谢谢,穆尔塔扎

Ank*_*kur 5

您的递归没有返回表达式,即当if when为false时,递归终止并返回nil.你可以使用ifas 修复此问题:

(defn foo
  ([x] (foo x []))
  ([x current]
     (if (> x 0)
       (recur (dec x) (conj current x))
       current)))
Run Code Online (Sandbox Code Playgroud)

这将返回[5 4 3 2 1],(foo 5)因为您使用向量作为返回值,并conj在向量上将项目添加到向量的末尾.您可以反转向量或使用列表,即代替(foo x [])使用(foo x '())

  • 我通常首先选择退出条件,因为我觉得它更容易阅读. (2认同)