Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Clojure 如何从构建结果列表的递归函数中获取尾部?_Clojure - Fatal编程技术网

Clojure 如何从构建结果列表的递归函数中获取尾部?

Clojure 如何从构建结果列表的递归函数中获取尾部?,clojure,Clojure,当前,当我传递数字2时,下面的代码将从2-10返回一个列表。我不希望它返回列表中的第一个元素2 boot.user=> (defn hierarchy [num] #_=> (when num #_=> (lazy-seq (cons num (hierarchy (#(when (< % 10) (inc %)) num)))))) #'boot.user/hierarchy boot.user=> (hierarchy 2) (2 3 4 5 6

当前,当我传递数字2时,下面的代码将从2-10返回一个列表。我不希望它返回列表中的第一个元素
2

boot.user=> (defn hierarchy [num]
#_=>   (when num
#_=>     (lazy-seq (cons num (hierarchy (#(when (< % 10) (inc %)) num))))))
#'boot.user/hierarchy

boot.user=> (hierarchy 2)
(2 3 4 5 6 7 8 9 10)

我知道如果我调用
rest
函数,我会得到尾部,但是我想不出更好的重构这个函数的方法来只返回尾部

首先,为了可读性,我将以这种方式重写您的函数:

(defn hierarchy [num]
  (when (< num 10)
    (lazy-seq (cons num (hierarchy (inc num))))))

user> (hierarchy 3)
;;=> (3 4 5 6 7 8 9 10)
(定义层次结构[num]
(当((层次结构3)
;;=> (3 4 5 6 7 8 9 10)
然后您可以将递归抽象到内部函数,而外部函数将执行第一个增量:

(defn hierarchy [num]
  (letfn [(h-inner [num] (when (< num 10)
                           (lazy-seq (cons num (h-inner (inc num))))))]
    (h-inner (inc num))))

user> (hierarchy 3)
;;=> (4 5 6 7 8 9 10)
(定义层次结构[num]
(letfn[(h-内部[num](当((层次结构3)
;;=> (4 5 6 7 8 9 10)

此外,最好使用
范围
迭代
来解决此任务,但我想这是一个练习递归的教育示例。

首先,为了可读性,我会以这种方式重写函数:

(defn hierarchy [num]
  (when (< num 10)
    (lazy-seq (cons num (hierarchy (inc num))))))

user> (hierarchy 3)
;;=> (3 4 5 6 7 8 9 10)
(定义层次结构[num]
(当((层次结构3)
;;=> (3 4 5 6 7 8 9 10)
然后您可以将递归抽象到内部函数,而外部函数将执行第一个增量:

(defn hierarchy [num]
  (letfn [(h-inner [num] (when (< num 10)
                           (lazy-seq (cons num (h-inner (inc num))))))]
    (h-inner (inc num))))

user> (hierarchy 3)
;;=> (4 5 6 7 8 9 10)
(定义层次结构[num]
(letfn[(h-内部[num](当((层次结构3)
;;=> (4 5 6 7 8 9 10)
同样,这个任务最好通过
范围
或者
迭代
来解决,但我想这是一个练习递归的教育示例