OCaml匹配元组?为什么没有使用此匹配项?

问题描述 投票:0回答:1

我在OCaml中具有以下代码:

let matchElement x y= 
  match x with 
    | (y,_) -> true 
    | _ -> false;;

并且我收到警告,该案例_将始终未使用。

我的意图是,如果x匹配第一个元素等于y的元组,则它返回true,否则返回false。你知道怎么做吗?

tuples match ocaml
1个回答
0
投票

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
© www.soinside.com 2019 - 2024. All rights reserved.