我在OCaml中具有以下代码:
let matchElement x y=
match x with
| (y,_) -> true
| _ -> false;;
并且我收到警告,该案例_将始终未使用。
我的意图是,如果x匹配第一个元素等于y的元组,则它返回true,否则返回false。你知道怎么做吗?
y
实际上是与之匹配的新名称,恰好与y
相同。它等效于:
let matchElement x y =
match x with
| (z, _) -> true (* A completely unrelated binding *)
| _ -> false;;
在这里您可以看到x
的所有值都与第一个模式匹配。
要做你想做的事,你可以这样写:
let matchElement x y =
match x with
| (y', _) when y' = y -> true
| _ -> false
(* Or equivalently *)
let matchElement (x, _) y = x = y