模式匹配和构造函数 [英] Pattern matching and constructors
问题描述
编写这种模式匹配时为什么会出错:
Why do i get errors when I write this kind of pattern matching :
type t = A of int | B of float
let f = function
| (A i | B f) -> true
| _ -> false
或
let f = function
| A i | B f -> true
| _ -> false
错误:变量f必须出现在此|的两边.模式
let f = function
| (A i | B i) -> true
| _ -> false
或
let f = function
| A i | B i -> true
| _ -> false
错误:此模式与float类型的int类型的值匹配但是期望有一个与值匹配的模式
推荐答案
如果您为多个模式提供一个右侧,则OCaml要求模式始终绑定到模式变量.
If you provide a single right-hand side for multiple patterns (as you do), OCaml requires that the patterns consistently bind to pattern variables.
在第一种情况下,
match ... with
| A i | B f -> ...
...
模式与它们绑定的变量不一致:第一个模式绑定到 i
,而第二个模式绑定到 f
.
the patterns don't agree on the variables they bind to: the first pattern binds to i
, while the second binds to f
.
在第二种情况下,
match ... with
| A i | B i -> ...
...
模式在绑定到变量的值类型上不一致:第一个模式将 int
类型的值绑定到 i
float
到 i
的类型的值.
the patterns don't agree on the type of values to bind to their variables: the first pattern binds a value of type int
to i
, while the second binds a value of type float
to i
.
这两个模式可以始终如一地绑定到变量的唯一方法是根本不绑定任何变量:
The only way in which these two pattern can consistently bind to variables is not to bind to any variables at all:
match ... with
| A _ | B _ -> ...
...
完整的示例将变为
type t = A of int | B of float
let f = function
| A _ | B _ -> true
| _ -> false
(但是请注意,模式匹配的最后一臂是多余的,因为前两个模式已经完全匹配了 t
类型的所有值.因此,我们得到:
(But note that the last arm of the pattern match is superfluous as the first two pattern already exhaustively match all values of your type t
. Hence, we get:
let f = function
| A _ | B _ -> true
这当然等同于编写 let f _ = true
.)
这篇关于模式匹配和构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!