madlisp/mad/fib.mad
2020-12-06 11:04:04 +07:00

17 lines
656 B
Plaintext

;; Functions to calculate Fibonacci numbers
;; 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.")