[英]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:你需要两个技巧来让它工作:
inline
and mark the outer function inline
inline
的内部递归 function 并将外部 function 标记为inline
1.0
which constraints the type to float
to LanguagePrimitives.GenericOne
, which is (as the name suggests) a generic 1 value1.0
,它将类型限制为float
到LanguagePrimitives.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.