当前,当我传递数字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)预期结果是
(3 4 5 6 7 8 9 10)我知道,如果我调用rest函数,我会得到尾巴,但我想不出一个更好的重构这个函数,只给我尾巴。
发布于 2017-11-24 16:11:42
首先,为了提高可读性,我将用这种方式重写您的函数:
(defn hierarchy [num]
(when (< num 10)
(lazy-seq (cons num (hierarchy (inc num))))))
user> (hierarchy 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)同样,这个任务最好用range或iterate来解决,但我想这是一个实践递归的教育例子。
https://stackoverflow.com/questions/47476672
复制相似问题