Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with inline keyword in F#

Tags:

f#

I'm trying to create a function which could take both ints and floats as parameters. The problem is that the compiler automatically infers the type because of a number in the function despite using the inline keyword. Here's what I mean:

(* Infers ints for every parameter because of '1' *)
let inline Lerp a b t = (1 - t) * a + t * b
(* Infers floats for every parameter because I added '.0' to '1' *)
let inline Lerp' a b t = (1.0 - t) * a + t * b

I can create two separate functions but it's kind of disappointing. Is there a way around this?

like image 805
tigerros Avatar asked Jan 25 '23 06:01

tigerros


1 Answers

You need LanguagePrimitives.GenericOne, which resolves to the value 'one' for any primitive numeric type or any type with a static member called 'One':

let inline Lerp a b t =
  (LanguagePrimitives.GenericOne - t) * a + t * b

Lerp 1 2 3 |> printfn "%A"         // 4
Lerp 1.1 2.2 3.3 |> printfn "%A"   // 4.73
like image 117
Brian Berns Avatar answered Feb 03 '23 06:02

Brian Berns