【问题标题】:OCaml matching tuples? Why is this match case unused?OCaml 匹配元组?为什么这个火柴盒不用?
【发布时间】:2020-04-05 16:50:13
【问题描述】:

我在 OCaml 中有以下代码:

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

我收到一个警告,即 case _ 将始终未被使用。

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

【问题讨论】:

    标签: tuples match ocaml


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      • 2023-01-08
      • 2012-12-07
      • 1970-01-01
      • 2016-01-14
      相关资源
      最近更新 更多