4

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.

2 Answers 2

10

This will work just fine:

let inline isAbsoluteProductGreaterThanSum a b =
    abs(a * b) > (a + b)

signature for this one will be like:

val isAbsoluteProductGreaterThanSum: 
    a:  ^a (requires static member ( * ) and static member ( + ) )->
    b:  ^b (requires static member ( * ) and static member ( + ) )
    -> bool
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.