Created
May 20, 2014 15:53
-
-
Save kpmaynard/f8b539326bf2e903f402 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
( 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? | |
) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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))