简体   繁体   English

通用 F# function

[英]Generic F# function

I'm very new to F#, and I need to write an exponentiation function that accepts any types of variables.我是 F# 的新手,我需要编写一个接受任何类型变量的求幂 function。

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为了能够使用递归,你可以定义一个非内inline的内部递归 function 并将外部 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为了能够将其用作通用功能,您还需要替换1.0 ,它将类型限制为floatLanguagePrimitives.GenericOne ,这是(顾名思义)通用 1 值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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