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!
CodePudding user response:
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 functioninline
- To be able to use this as generic fucntion, you also need to replace
1.0
which constraints the type tofloat
toLanguagePrimitives.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