On Mon, Aug 9, 2010 at 6:00 PM, Phil Hagelberg <p...@hagelb.org> wrote:
> Just remove the call to recur and it will work, albeit only for lists
> small enough to not blow the stack.

I'm assuming from the tone of the original post that the author is
trying to generally understand how to write recursive functions in
Clojure, rather than use built-ins, and that processing
arbitrary-sized lists is a primary goal.  The posted code (minus the
call to recur), is an elegant recursive formulation that is idiomatic
in Scheme because Scheme is (typically) implemented in a way that
makes stack limitations (mostly) a non-issue.

In Clojure, you have to work around stack limitations imposed by Java,
and recursive functions must be "translated" to work on largish lists
in Clojure.  There is no one recipe to make that translation, but
there are several common patterns.  If the recursive call is in tail
position, you can usually write the function the same way, but replace
the self-call with the word "recur".  If not in tail position and the
function is a list-building function, you may be able to solve the
stack problem with a call to lazy-seq -- I touched on this topic in a
recent blog post:
http://programming-puzzler.blogspot.com/2010/07/translating-code-from-python-and-scheme.html

The solution to most recursive problems in Clojure is to build your
answer in an accumulator, so you must learn how to design and develop
accumulator-style recursive functions.  For an in-depth look at this
process (in Scheme), I recommend:
http://www.htdp.org/2001-11-21/Book/node156.htm

For mutually recursive problems, a trampoline may be an option.

If none of these options work, you may have to simulate your own call
stack (ugh).

It can sometimes be frustrating to write code in a language that is
built around recursion rather than iteration constructs, and then has
such severe limitations on how and when recursion can be safely used,
but with practice, the vast majority of code can be easily rewritten
in a manner conducive to Clojure.

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