【发布时间】:2016-08-02 09:42:42
【问题描述】:
为了学习,我正在尝试使用 pointfree inline 函数重新发明 List.fold、List.reduce 和 List.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.
我应该添加什么来满足编译器?
【问题讨论】:
-
我似乎无法重现该问题,因为即使
reduce也无法为我编译。我有预期的'a -> 'b -> 'a -> 'a但给定('c -> 'd -> 'c) -> 'c -> 'd list -> 'c类型'a与指向折叠 的类型'b -> 'c -> 'b不匹配 -
顺便说一句,List.reduce 的 F# 实现在空列表上失败,并且不需要 GenericZero。例如,你可以这样定义reduce: let rec reduce op = function | [] -> 以“空”失败 | [x] -> x | h :: t -> op h(减少 op t)
-
@Sehnsucht 抱歉,这是我的错字,我添加了类型注释来修复
reduce处的编译错误
标签: f#