2008/10/13 Stuart Halloway <[EMAIL PROTECTED]>:
>
> Hi Michael,
>
> The multiplication by n comes after the recur.
>
> Cheers,
> Stuart
>
>>
>> Giving the factorial function as:
>>
>> (def factorial
>> (fn [n] (cond (= n 1)
>> (> n 1) (* n (recur (dec n))))))
>>
>> the compiler complains "Can only recur from tail position".
>> Isn't really the recur in tail position? It is the last expresson to
>> be evaluated.
>>
>> >
>
>
> >
>
Hello,
Following on from what Stuart said, here is a version with recur that
uses an accumulator to avoid your problem:
(defn factorial
([n]
(factorial n 1))
([n acc]
(if (= n 0) acc
(recur (dec n) (* acc n)))))
Also, your method would return nil for (factorial 0), which should be
1, so I adjusted the termination condition to: (= n 0).
Regards,
Stewart Griffin
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---