Skip to content

Instantly share code, notes, and snippets.

@kpmaynard
Created May 20, 2014 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kpmaynard/f8b539326bf2e903f402 to your computer and use it in GitHub Desktop.
Save kpmaynard/f8b539326bf2e903f402 to your computer and use it in GitHub Desktop.
( defn fib [n]
(def memo (ref {})) ;create a ref to memo
(for [k (range (inc n))]
(do
(if (> k 1)
(dosync (alter memo conj [k (+ (@memo (- k 1)) (@memo (- k 2)))]) ;update memo with new pair
)
(dosync (alter memo conj [k k]) ; update memo with first two pairs
)
)
(when (= k n) (println "Fibonacci " n " " (@memo n))) ; I am trying to look up the value associated with n
; but it appears that memo is being dereferenced on each
; iteration? Where are the nulls coming from?
)
)
)
@kpmaynard
Copy link
Author

GFredericks immutable version
(defn fib [n](get
%28reduce %28fn [memo n] %28assoc memo n %28+ %28memo %28dec n%29%29 %28memo %28- n 2%29%29%29%29%29 {0 1N 1 1N} %28range 2 %28inc n%29%29%29 n))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment