mirror of
https://github.com/peklaiho/madlisp.git
synced 2024-11-22 05:14:45 +00:00
better Fibonacci function
This commit is contained in:
parent
086765d286
commit
1151ebe336
19
mad/fib.mad
19
mad/fib.mad
@ -1,16 +1,11 @@
|
||||
;; Functions to calculate Fibonacci numbers
|
||||
|
||||
;; Recursive, tail call optimized
|
||||
(defn fibRec (i n a b) (if (= i n) (+ a b) (fibRec (inc i) n b (+ a b))))
|
||||
(defn fib (n) (if (< n 2) n (fibRec 2 n 0 1)))
|
||||
|
||||
;; Return a vector of n Fibonacci numbers
|
||||
(defn fibVec (n) (map fib (range n)))
|
||||
|
||||
;; Slow recursive version
|
||||
(defn slowFib (n) (if (< n 2) n (+ (slowFib (- n 1)) (slowFib (- n 2)))))
|
||||
|
||||
;; Return the sum of the last 2 numbers in a sequence
|
||||
(defn sumOfLast (l) (+ (last l) (penult l)))
|
||||
|
||||
;; Faster version, return vector of n numbers, tail call optimized
|
||||
(defn fibListRec (n l) (if (< (len l) n) (fibListRec n (push l (sumOfLast l))) l))
|
||||
(defn fibList (n) (fibListRec n [0 1]))
|
||||
(defn fastFib (n) (sumOfLast (fibList n)))
|
||||
|
||||
;; Add docstrings
|
||||
(doc slowFib "Return the nth number from the Fibonacci sequence recursively.")
|
||||
(doc fastFib "Return the nth number from the Fibonacci sequence iteratively.")
|
||||
|
Loading…
Reference in New Issue
Block a user