On Sun, Dec 28, 2008 at 6:01 PM, Craig Marshall <cra...@gmail.com> wrote:
>
> Hi,
>
> I'm trying to learn lisp and Clojure and so I'm trying some excercises
> suggested here on the group a while ago.
>
> I'm not doing too well, I had to cheat on excercise one (make a series
> of integers) by looking at the source code to the range function, and
> I'm now having to ask for help with excercise two!
>
> I know I could just find a different implementation online, but I
> would prefer to understand why my method doesn't work. If anyone can
> point to my mistake(s), I'd be very grateful..
>
> (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?

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

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 :)

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

i.e. if I want to calculate the nth fibonacci number, I have to first
calculate the (n-1)th and (n-2)th fibonacci numbers and then add them
together and return the result.  At some point this has to terminate,
so you need to make sure that there is a way out of the recursion.
(You're probably already familiar with recursion, in which case, sorry
for stating the obvious :)

clojure.contrib.lazy-seqs has a lazy infinite sequence implementation.

-- 
Michael Wood <esiot...@gmail.com>

--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---

Reply via email to