On Jan 11, 7:19 pm, e <evier...@gmail.com> wrote:
> oh.  I missed the "recur my-list" in your answer.  So we still don't
> have an iterative solution.  Recursion should never be necessary.  I
> agree that it simplifies things sometimes and you can use it when you
> are stuck. . . . .but no need to push a whole stack frame for such a
> simple problem, I would posit.

Actually, that's the nice thing about loop/recur: it looks recursive
but is actually iterative.

So a recursive function like this:

(defn sum [total list]
  (if list
    (sum (+ total (first list))
         (rest list))
    total))

Can be turned into an iterative one via recur:

(defn sum [total list]
  (if list
    (recur (+ total (first list))
           (rest list))
    total))

Note that if there is no matching loop construct, it uses the
containing function instead.

Most functional languages actually optimize functions like the one
above automatically, without a need for an explicit recur. It's called
tail call optimization; if a function calls itself last of all,
there's no need to keep the stack around. Unfortunately, the JVM
doesn't have this capability, so we need to explicitly tell Clojure to
do it via recur.

Note that for recur to work, it needs to be the last thing called. So
a more naive implementation of sum wouldn't be able to use recur:

(defn sum [list]
  (if list
    (+ (first list) (sum (rest list)))
    0))

In this case, the last function called is +, so you can't substitute
"sum" for "recur" in this case.

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