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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With