madlisp/mad/fib.mad

13 lines
499 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-06-06 08:59:05 +00:00
(def slowFib (fn (n) (if (< n 2) n (+ (slowFib (- n 1)) (slowFib (- n 2))))))
2020-06-06 09:25:49 +00:00
;; Return the sum of the last 2 numbers in a sequence
2020-10-17 07:15:14 +00:00
(def sumOfLast (fn (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-06-06 08:59:05 +00:00
(def fibListRec (fn (n l) (if (< (len l) n) (fibListRec n (push l (sumOfLast l))) l)))
(def fibList (fn (n) (fibListRec n [0 1])))
2020-10-17 07:15:14 +00:00
(def fastFib (fn (n) (sumOfLast (fibList n))))