如何实现静态解析的类型参数?

时间:2018-04-23 14:18:48

标签: f#

如何实现静态解析的类型参数?

具体来说,我想让函数适用于所有数字类型。

我尝试过以下方法:

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)

我确实查看了此documentation,但仍然无法解决我的问题。

2 个答案:

答案 0 :(得分:10)

这样可以正常工作:

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

这个签名就像:

val isAbsoluteProductGreaterThanSum: 
    a:  ^a (requires static member ( * ) and static member ( + ) )->
    b:  ^b (requires static member ( * ) and static member ( + ) )
    -> bool

答案 1 :(得分:1)

我想也许您需要明确地使用约束,所以在这里:

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