On Wed, Jun 30, 2010 at 1:44 AM, Tim Robinson <tim.blacks...@gmail.com>wrote:

> So I am reading On Lisp + some blogs while learning Clojure (I know,
> scary stuff :)
>
> Anyway, I've been playing around to see if I can get an anonymous
> recursive function to work, but alas I am still a n00b and not even
> sure what Clojure's approach to this would be.
>
> How would I do this in Clojure?:
>
> My first attempt:
>
> ((fn [x]
>   (if (= x 0)
>       1
>       (* 2 (recur (dec z))))) 5)
>
> Then my second:
>
> ((fn [x]
>       (let [z (if (= x 0)
>                   1
>                   (* 2 x))]
>          (recur (dec z))))  5)
>
> Ideally one could do:
>
> ((recursive-fn #( if (= % 0) 1 (* 2 %)) (recur it))  5)
>
>
> Obviously none work, and I believe I understand why. I just don't
> understand how to actually do this or if for some reason Clojure
> avoids this for some reason.
>
> I am not actually trying to accomplish a specific task, so the example
> was made to be simple not meaningful. I'm just playing around to learn
> recursive functions and Clojure style.
>

Hi Tim,

You're running into an error that you can only recur from the tail position?
That's because you're trying to use the result of recur to do further
computation. Clojure doesn't allow this with recur, because recur is more of
a loop or goto construct behind the scenes. If you really want to run your
algorithm that way you just have to give the fn a name and then call the
name.

This should work:

((fn my-fn [x]
  (if (= x 0)
      1
      (* 2 (my-fn (dec x))))) 5)

That accomplishes the question as asked, but you may also want to look into
calling reduce as a different approach to the problem.

-- 
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
Note that posts from new members are moderated - please be patient with your 
first post.
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