genericsf#exponentiation

Generic F# function


I'm very new to F#, and I need to write an exponentiation function that accepts any types of variables.

let exp value pow =

    let mutable result = 1.0

    for i = 1 to abs pow do
        result <- value * result

    if pow > 0 then result else 1.0 / result

let rec quickExp value pow =

    let result =
        if pow = 0 then
            1.0
        else
            let half = quickExp value (abs pow / 2)

            if pow % 2 = 0 then half * half else value * half * half

    if pow > 0 then result else 1.0 / result

Tried inline, but it doesn't work with recursion. I would be grateful for any help!


Solution

  • You need two tricks to get this to work:

    The following seems to work for me:

    let inline quickExp (value:^a) (pow:int) : ^a =
      let rec loop pow = 
        let result : ^a =
            if pow = 0 then
                LanguagePrimitives.GenericOne
            else
                let half = loop (abs pow / 2)
                if pow % 2 = 0 then half * half else value * half * half
        if pow > 0 then result else LanguagePrimitives.GenericOne / result
      loop pow
    
    quickExp 2.0 2
    quickExp 2 2