On Sat, Jun 19, 2010 at 11:22 PM, Mike Meyer
<[email protected]> wrote:
>
> "Rob Lachlan" <[email protected]> wrote:
>
>>Actually, Mike, your two functions work just fine. (Equal branch).
>>Mind you I checked that out over two hours ago, so this information
>>might be out of date.
>>
>>Rob
>>
>>On Jun 19, 6:59 pm, Mike Meyer <mwm-keyword-googlegroups.
>
> Ok, why does this work but the fact fail? Or does the fact example still fail
> on that build?
>
> The fact that this requires explanation is a pretty good argument the fact
> behavior.
>
>> (defn fact [n]
>> (loop [n n r 1]
>> (if (zero? n)
>> r
>> (recur (dec n) (* r n)))))
(The quoting in this thread is getting out-of-hand, everyone please
reply on the bottom)
The difference between your examples and the fact examples is that
(inc prim) -> prim
while
(* prim boxed) -> boxed
In the fact example, the type of n as an initializer in the loop
statement is unknown at compile time and thus must be boxed. The fact
that you need to know that, is very much what some people are arguing
against.
The choices are to do either:
(loop [n n r (num 1)]
or
(loop [n (long n) r 1]
Either option will make (* r n) return a primitive or boxed value of
the appropriate type. Both versions will overflow and throw an
exception at (fact 21).
To have a fact that works for large numbers you need:
(defn fact [n]
(loop [n n r (num 1)]
(if-not (pos? n)
r
(recur (dec n) (*' r n)))))
Most of the versions posted so far were broken for negative n by the way.
--
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