我在编写结果类型和各种函数时遇到了问题,并遇到了我无法解释的类型不匹配错误。下面是一个最小的例子:结果类型中的类型不匹配错误
type ('a, 'b) result =
| Success of 'a
| Failure of 'b list
let apply fr xr =
match fr, xr with
| Success f, Success x -> Success (f x)
| Failure _, Success _ -> fr
| Success _, Failure _ -> xr
| Failure a, Failure b -> Failure (List.concat [a; b])
编译此代码产生以下错误:如果您更改按照以下申请功能
init.fsx(8,31): error FS0001: Type mismatch. Expecting a
('a,'b) result
but given a
(('c -> 'a),'d) result
The resulting type would be infinite when unifying ''a' and ''b -> 'a'
,它编译正确:
let apply fr xr =
match fr, xr with
| Success f, Success x -> Success (f x)
| Failure a, Success _ -> Failure a
| Success _, Failure b -> Failure b
| Failure a, Failure b -> Failure (List.concat [a; b])
为什么使用匹配的超值(这里是fr或xr)无法正常工作,但构建新的失败值呢?
谢谢约翰。目前还不清楚为什么第一场比赛可以替代 '| |成功f,成功x - >成功(f x)' 应该对第二场比赛有任何影响 '| |失败_,成功_ - > fr' 对我来说听起来像编译器中不必要的限制... – dumetrulo
问题是'fr'与'Success(fx)'具有不同的类型,并且表达式需要返回变量相同的类型。 –