You don't need to recur to another function, just recur to a loop:
(defn factorial [n]
(loop [x n acc 1]
(if (zero? x) acc (recur (dec x) (* acc x)))))
(println (factorial 5))
--
Science answers questions; philosophy questions answers.
On Jul 15, 2010, at 6:38 AM, Brisance wrote:
> Here's a factorial function as found in the WikiBook "Learning
> Clojure" <http://en.wikibooks.org/wiki/Learning_Clojure>:
>
> (defn factorial [n]
> (defn fac [n acc]
> (if (zero? n)
> acc
> (recur (- n 1) (* acc n)))) ; recursive call to fac, but reuses
> the stack; n will be (- n 1), and acc will be (* acc n)
> (fac n 1))
>
> Question: how would I go about writing idiomatic Clojure to return
> factorials of n, for large values of n. e.g. 1e6 or more? Preferably
> without having to create another function.
>
> Thanks in advance for any insight.
>
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to [email protected]
> Note that posts from new members are moderated - please be patient with your
> first post.
> 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
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
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