• nychtelios@rlyeh.icu
      link
      fedilink
      arrow-up
      1
      ·
      edit-2
      1 year ago

      This isn’t goofy, this is an extremely diffused “pattern” when you need to use non dynamic number sequences.

  • Ephera
    link
    fedilink
    arrow-up
    2
    ·
    3 years ago

    I was gonna say you could probably actually have that properly calculated and O(1), if you stuck the result in a lazy list. But then I realized this hard-coded implementation probably already exhausts ulong, so there really is no point to that.

  • Abbé
    link
    fedilink
    arrow-up
    1
    ·
    3 years ago
    ghci> φ = (1 + sqrt 5) / 2
    ghci> ψ =  1 - φ
    ghci> fib n = (φ ** n - ψ ** n) / (sqrt 5)
    
  • ☆ Yσɠƚԋσʂ ☆
    link
    fedilink
    arrow-up
    1
    ·
    3 years ago

    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