madlisp/mad/fib.mad

17 lines
656 B
Plaintext
Raw Normal View History

2020-06-06 09:25:49 +00:00
;; Functions to calculate Fibonacci numbers
2020-06-06 08:59:05 +00:00
2020-06-06 09:25:49 +00:00
;; Slow recursive version
2020-12-06 04:04:04 +00:00
(defn slowFib (n) (if (< n 2) n (+ (slowFib (- n 1)) (slowFib (- n 2)))))
2020-06-06 08:59:05 +00:00
2020-06-06 09:25:49 +00:00
;; Return the sum of the last 2 numbers in a sequence
2020-12-06 04:04:04 +00:00
(defn sumOfLast (l) (+ (last l) (penult l)))
2020-06-06 08:59:05 +00:00
2020-06-08 02:55:29 +00:00
;; Faster version, return vector of n numbers, tail call optimized
2020-12-06 04:04:04 +00:00
(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)))
2020-12-06 04:04:04 +00:00
;; Add docstrings
(doc slowFib "Return the nth number from the Fibonacci sequence recursively.")
(doc fastFib "Return the nth number from the Fibonacci sequence iteratively.")