Clojure递归实现斐波那契数列

;递归,消耗栈空间
(defn stack-consuming-fibo [n]
  (cond
   (= n 0) 0 
   (= n 1) 1
   :else (+ (stack-consuming-fibo (- n 1))
        (stack-consuming-fibo (- n 2)))))  
;尾递归,JVM不能自动TCO
(defn tail-fibo [n]
  (letfn [(fib
            [current next n]
            (if (zero? n)
              current
              (fib next (+ current next) (dec n))))]
    (fib 0N 1N n)))
;自递归与recure
(defn recur-fibo [n]
  (letfn [(fib
          [current next n]
          (if (zero? n)
            current
            (recur next (+ current next) (dec n))))]
    (fib 0N 1N n)))
;惰性队列
(defn lazy-seq-fibo
  ([]
   (concat [0 1] (lazy-seq-fibo 0N 1N)))
  ([a b]
   (let [n (+ a b)]
     (lazy-seq
      (cons n (lazy-seq-fibo b n))))))
;惰性队列&现有序列库
(defn fibo []
  (map first (iterate (fn [[a b]] [b (+ a b)]) [0N 1N])))

你可能感兴趣的:(Clojure递归实现斐波那契数列)