简体   繁体   中英

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!

You need two tricks to get this to work:

  • To be able to use recursion, you can define an inner recursive function that is not inline and mark the outer function inline
  • To be able to use this as generic fucntion, you also need to replace 1.0 which constraints the type to float to LanguagePrimitives.GenericOne , which is (as the name suggests) a generic 1 value

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM