>> (defn fib-helper [a b]
>>  (fib-helper b (+ a b)))

> This defines an infinitely recursive function.  It never actually
> returns anything, so it quickly exhausts the stack.  Were you trying
> for a lazy infinite sequence of fibonacci numbers?

Yes - exactly, I couldn't figure it out, even after trying the same
"algorithm" in python.. I don't like giving up on it though! I would
like to see something like this version "working" somehow. I will
probably come back to it when I have learned more.

>> (defn fib (fib-helper 0 1)) ; This doesn't work either: (defn fib (fib-
>> helper '(0 1)))

> It looks like you want to use (def fib ...) instead of (defn fib ...),
> but because of the infinitely recursive fib-helper this will not get
> you much further :)

Yes - I fixed this (or put in the empty arg list - I don't remember),
and got a heap overflow error or similar. So you were right. If I'd
seen that message before I'd have figured out there was an infinite
recursion somewhere.

> For exercise two, perhaps you should try for the traditional recursive
> definition of fib?

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 [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to