OCaml匹配元组?为什么这个火柴盒没有被使用?
OCaml matching tuples? Why is this match case unused?
我在 OCaml 中有以下代码:
let matchElement x y=
match x with
| (y,_) -> true
| _ -> false;;
并且我收到一条警告,即案例 _ 将始终未使用。
我的意图是,如果 x 匹配第一个元素等于类型 y 的元组,那么它 returns 为真,否则,它 returns 为假。你知道怎么做吗?
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
我在 OCaml 中有以下代码:
let matchElement x y=
match x with
| (y,_) -> true
| _ -> false;;
并且我收到一条警告,即案例 _ 将始终未使用。
我的意图是,如果 x 匹配第一个元素等于类型 y 的元组,那么它 returns 为真,否则,它 returns 为假。你知道怎么做吗?
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