gpt4 book ai didi

f# - op_addition 的静态成员约束

转载 作者:行者123 更新时间:2023-12-01 04:38:21 28 4
gpt4 key购买 nike

我正在尝试使用 pointfree inline reshape List.foldList.reduceList.sum > 为了学习而发挥作用。这是我的:

let flip f y x = f x y

let rec fold folder seed = function
| [] -> seed
| h :: t -> fold folder (folder seed h) t

let inline reduce< ^a when ^a : (static member Zero : ^a) > :
(^a -> ^a -> ^a) -> ^a list -> ^a =
flip fold LanguagePrimitives.GenericZero

let inline sum< ^a when
^a : (static member (+) : ^a * ^a -> ^a) and
^a : (static member Zero : ^a)> : ^a list -> ^a =
reduce (+)
// ^ Compile error here

我知道这种冗长的类型约束在 F# 中并不常用,但我正在努力学习,所以请多多包涵。

我遇到了一个我不明白的非常神秘的编译错误:

Type mismatch. Expecting a
'a -> 'a -> 'a
but given a
'a -> 'b -> 'c
A type parameter is missing a constraint 'when ( ^a or ^?269978) : (static member ( + ) : ^a * ^?269978 -> ^?269979)'
A type parameter is missing a constraint 'when ( ^a or ^?269978) : (static member ( + ) : ^a * ^?269978 -> ^?269979)'
val ( + ) : x:'T1 -> y:'T2 -> 'T3 (requires member ( + ))
Full name: Microsoft.FSharp.Core.Operators.( + )
Overloaded addition operator
x: The first parameter.
y: The second parameter.

我应该添加什么来满足编译器?

最佳答案

我不知道有什么方法可以完全按照您的意愿进行操作,因为我不知道如何以 pointfree 样式调用静态约束的静态成员。请注意,您没有调用 ^a(+) 并且编译器不知道如何解决这个问题......如果您喜欢使用内部辅助函数,你可以这样做:

let inline sum< ^a
when ^a : (static member (+) : ^a -> ^a -> ^a) and
^a : (static member Zero : ^a) > : ^a list -> ^a =
let add x y = (^a : (static member (+) : ^a -> ^a -> ^a) (x, y))
reduce add

注意警告

warning FS0077: Member constraints with the name 'op_Addition' are given special status by the F# compiler as certain .NET types are implicitly augmented with this member. This may result in runtime failures if you attempt to invoke the member constraint from your own code.

确实:

总和 [1; 2; 3] 导致

System.NotSupportedException: Specified method is not supported.
     at FSI_0005.it@15-1.Invoke(Int32 x, Int32 y) in ...

但是如果你把 sum 改成:

let inline sum list =
reduce (+) list

sum [1; 2; 3] // 6

关于f# - op_addition 的静态成员约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38701715/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com