跳转到内容

Clojure 编程/示例/API 示例/递归工具

来自 Wikibooks,为开放世界提供开放书籍

参见 recur

; compute the factorial of 5, establishes two 'variables' cnt and acc
; cnt is decremented every call until it reaches 0
; acc stores the result of multiplying each value cnt took
(loop [cnt 5,
       acc 1]
  (if (zero? cnt)
    acc
    (recur (dec cnt) (* acc cnt))))

lazy-cons

[编辑 | 编辑源代码]
(defn fib-seq []
  ((fn rfib [a b] 
       (lazy-cons a (rfib b (+ a b)))) 
    0 1))
 
user> (take 20 (fib-seq))
(0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181)
华夏公益教科书