什么是为泛型类型编写类型约束的正确方法,以便我们可以将其实例传递给Array.sum
函数?
这不起作用:
let mySum< 'a when 'a : (static member get_Zero: unit -> 'a) and 'a : (static member (+) : 'a -> 'a -> 'a) > (xs: 'a[]) = Array.sum xs
我在上面得到的错误消息是A type parameter is missing a constraint 'when ^a : (static member get_Zero : -> ^a)'
虽然我需要一个泛型类型,而不是一个静态解析的类型,但我确实尝试了以下方法,但没有成功:
let mySum< ^a when ^a : (static member get_Zero: unit -> ^a) and ^a : (static member (+) : ^a -> ^a -> ^a) > (xs: ^a[]) = Array.sum xs
(我在这里再次得到相同的错误消息)。我也尝试内联该函数,但它也不起作用。
发布于 2021-07-21 07:32:43
这是可行的:
let inline mySum< 'a when 'a : (static member Zero : ^a) and 'a : (static member (+) : 'a -> 'a -> 'a) > (xs: 'a[]) = Array.sum xs
但不要忘记将函数标记为内联。
https://stackoverflow.com/questions/68465394
复制相似问题