Craig, Something you should be aware of is that this implementation of Fibonacci is very inefficient. For more info as to why, you can read:
http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-11.html#%_sec_1.2.2 The short story is doing it this way performs a lot of wasted calculations as n gets larger: user=> (time (fib 40)) "Elapsed time: 54768.247 msecs" 102334155 If you use this implementation, it uses an iterative process, and is therefore much faster: user=> (defn fib [n] (loop [a 1 b 0 count n] (if (zero? count) b (recur (+ a b) a (dec count))))) #'user/fib user=> (fib 9) 34 user=> (time (fib 40)) "Elapsed time: 0.06 msecs" 102334155 On Dec 29, 5:01 am, "Craig Marshall" <cra...@gmail.com> wrote: > I finally got it working without looking at someone elses code. > > (defn fib [n] > (if (<= n 1) ; if 0 or 1 > n ; return same, else... > (let [n1 (fib (- n 1)) ; calculate n-1 fib > n2 (fib (- n 2))] ; and n-2 > (+ n1 n2)))) ; return sum of n-1 and n-2 > > (println (fib 9)) > > I had to start with the python equivalent: > > def fib(n): > if n <= 1: return n > n_1 = fib(n-1) > n_2 = fib(n-2) > return n_1 + n_2 > > print fib(9) # Should be 34 > > and translate to clojure, which hopefully is something I won't have to > do forever as I understand clojure more. > > Thanks, > Craig --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Clojure" group. To post to this group, send email to clojure@googlegroups.com To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en -~----------~----~----~----~------~----~------~--~---