Hi Lost,

1
2
3
4
5
6
7
8
9
10
> let rec fac num =
-   match num with
-   | 0 | 1 -> 1
-   | _ -> num * fac (num - 1);;

val fac : int -> int

> fac 10;;
val it : int = 3628800
>

Is this what you're looking for?

regards,
Danny

By on 8/19/2008 11:06 AM ()

yes, thanks

By on 8/19/2008 11:14 AM ()

One thing to be careful of here is that the implementation of fac above is not tail recursive, meaning it will cause the stack to blow when used to calculate large numbers. fac 1000000 caused a StackOverflowException on my machine. here's a tail recursive version that uses Math.BigInt:

1
2
3
4
5
6
7
8
open Math.BigInt

let facBig num =    
    let rec fac acc num =
        match num with
        | 0I | 1I  -> acc
        | _ -> fac (acc * num) (num - 1I)
    fac 1I num

Here the recursive call to fac is the last operation performed in second match case, so tail recursion optimization can be applied.

regards,

Danny

By on 8/19/2008 12:35 PM ()

Thanks, but this was just an code example.[;)]

By on 8/20/2008 4:24 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper