美文网首页
Clojure递归实现斐波那契数列

Clojure递归实现斐波那契数列

作者: Tankerdream | 来源:发表于2015-09-19 11:39 被阅读59次
    ;递归,消耗栈空间
    (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递归实现斐波那契数列

          本文链接:https://www.haomeiwen.com/subject/pvgbcttx.html