Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement statically resolved type parameters?

Tags:

f#

How do I implement statically resolved type parameters?

Specifically, I want to make a function work for all numeric types.

I've tried the following:

let isAbsoluteProductGreaterThanSum a b =
     Math.Abs(a * b) > (a + b)

let inline isAbsoluteProductGreaterThanSum a b =
     Math.Abs(a * b) > (a + b)

let inline isAbsoluteProductGreaterThanSum ^a ^b =
     Math.Abs(^a * ^b) > (^a + ^b)

let inline isAbsoluteProductGreaterThanSum (val1:^a) (val2:^b) =
     Math.Abs(val1 * val2) > (val1 + val2)

I did view this documentation but was still unable to resolve my question.

like image 571
Scott Nimrod Avatar asked Dec 18 '22 23:12

Scott Nimrod


1 Answers

I thought maybe you need explicitly made it with constraints, so here you go:

let inline isAbsoluteProductGreaterThanSum'< ^a, ^b, ^c
                                       when (^a or ^b): (static member (+): ^a * ^b -> ^c)
                                       and  (^a or ^b): (static member (*): ^a * ^b -> ^c)
                                       and   ^c       : (static member Abs: ^c      -> ^c)
                                       and   ^c       :  comparison>
                                       a b =
     let productOfAb = ((^a or ^b): (static member (*): ^a * ^b -> ^c) (a, b))
     let sumOfAb     = ((^a or ^b): (static member (+): ^a * ^b -> ^c) (a, b))
     abs (productOfAb) > sumOfAb
like image 110
Szer Avatar answered Jan 05 '23 00:01

Szer