AgreeableLandscapeM to Programmer Humor · 3 years agoThe O(1) Fibonacci implementationimagemessage-square8fedilinkarrow-up162arrow-down14
arrow-up158arrow-down1imageThe O(1) Fibonacci implementationAgreeableLandscapeM to Programmer Humor · 3 years agomessage-square8fedilink
minus-square☆ Yσɠƚԋσʂ ☆linkfedilinkarrow-up1·3 years agobest of both world with Lisp macros :) (defmacro gen-fib [size] (let [values (->> (iterate (fn [[a b]] [b (+ a b)]) [0 1]) (map first) (take size) (vec))] `(defn ~'fib [~'n] (~values ~'n)))) (macroexpand-1 '(gen-fib 10)) ;=> (clojure.core/defn fib [n] ([0 1 1 2 3 5 8 13 21 34] n)) (gen-fib 10) (fib 9) ;=> 34
best of both world with Lisp macros :)
(defmacro gen-fib [size] (let [values (->> (iterate (fn [[a b]] [b (+ a b)]) [0 1]) (map first) (take size) (vec))] `(defn ~'fib [~'n] (~values ~'n)))) (macroexpand-1 '(gen-fib 10)) ;=> (clojure.core/defn fib [n] ([0 1 1 2 3 5 8 13 21 34] n)) (gen-fib 10) (fib 9) ;=> 34