[英]F# Generic sum type constraints
What is the proper way to write type constraints for a generic type so that we can have its instance passed to the Array.sum
function?为泛型类型编写类型约束以便我们可以将其实例传递给Array.sum
函数的正确方法是什么?
This does not work:这不起作用:
let mySum< 'a when 'a : (static member get_Zero: unit -> 'a) and 'a : (static member (+) : 'a -> 'a -> 'a) > (xs: 'a[]) = Array.sum xs
The error message I get for the above is A type parameter is missing a constraint 'when ^a : (static member get_Zero : -> ^a)'
我收到的上述错误消息是A type parameter is missing a constraint 'when ^a : (static member get_Zero : -> ^a)'
Although I would need a generic type, not a statically resolved one, I did try the following, withouth success:虽然我需要一个泛型类型,而不是静态解析的类型,但我确实尝试了以下方法,但没有成功:
let mySum< ^a when ^a : (static member get_Zero: unit -> ^a) and ^a : (static member (+) : ^a -> ^a -> ^a) > (xs: ^a[]) = Array.sum xs
(I get the same error message here again). (我在这里再次收到相同的错误消息)。 I also tried to inline the function and it did not work either.我也尝试内联该函数,但它也不起作用。
This works:这有效:
let inline mySum< 'a when 'a : (static member Zero : ^a) and 'a : (static member (+) : 'a -> 'a -> 'a) > (xs: 'a[]) = Array.sum xs
but don't forget to mark the function inline.但不要忘记将函数标记为内联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.