Thursday, February 28, 2008

Some Fun Generating 'the power of' With F#

So for my first bit of fun with F# I figured it'd be fun to play with the BigNum (used for crazy big numbers) I figured I write up some quick functions that simple generate the power of some number, resulting in some crazy big numbers :)

(*all of my examples include '#light')

My first function doesn't use the BigNum but it's very simplistic.

let rec pwrof x y =
     if y = 1 then
         x
     else
         x * pwrof x (y - 1)

So for everyone new to F# 'pwrof' is a recursive function that takes 2 ints. 'rec' lets the compiler know that the function is recursive and the 2 parameters get resolved down to being ints at compile time. This came pretty naturally for me coming from a C# world, so lets try to mix it up a bit.

let rec pwrof x y =
     match y with
     | 1 -> x
     | _ -> x * pwrof x (y - 1)

This function does the exact same thing, but instead of using a familiar if/else statement we're using pattern matching (these are widely used in F#). It's like a switch statement. If y matches 1 then we return x, otherwise if y matches anything else, '_', then we recurse.

These were kinda fun, but I wanted to calculate crazy big power of calculations like 5000^5000. So here's an example that resembles my first function

let bpwrof x y =
    let x = Microsoft.FSharp.Math.BigNum.of_int x
    let pwr = x
    let rec pwrof x y =
        if y = 1 then
            x
        else
            pwrof (x * pwr) (y - 1)
    pwrof x y

And here's an example that resembles my second function

let bpwrof x y =
    let x = Microsoft.FSharp.Math.BigNum.of_int x
    let pwr = x
    let rec pwrof x y =
        match y with
        | 1 -> x
        | _ -> pwrof (x * pwr) (y - 1)
    pwrof x y

These are tail recursive so you can create some really, REALLY big numbers. If you call one of the last 2 functions you can calculate say 5000 to the 9000th power. It ends up taking a lot more time to print the result to the screen than it does to do the calculation(its pages and pages of number madness). I even tried 5000 to the 90,000th pwr, that's a big number.

 

Oh well, that's all for now...

No comments: