madlisp/mad/fib.mad

12 lines
382 B
Plaintext
Raw Permalink 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-12-07 02:38:39 +00:00
;; 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)))
2020-06-06 08:59:05 +00:00
2020-12-07 02:38:39 +00:00
;; Return a vector of n Fibonacci numbers
(defn fibVec (n) (map fib (range n)))
2020-12-07 02:38:39 +00:00
;; Slow recursive version
(defn slowFib (n) (if (< n 2) n (+ (slowFib (- n 1)) (slowFib (- n 2)))))