OCaml模式与非常量匹配 [英] OCaml Pattern match with non-constants

查看:86
本文介绍了OCaml模式与非常量匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以对变量而不是常量值进行模式匹配:

Is it possible to do pattern matching on variables instead of constant values:

# let x = 2 in
let y = 5 in
match 2 with
| x -> "foo"
| y -> "bar"
| _ -> "baz";;
            let y = 5 in
Warning 26: unused variable y.
  let x = 2 in
Warning 26: unused variable x.
  | y -> "bar"
Warning 11: this match case is unused.
  | _ -> "baz";;
Warning 11: this match case is unused.
- : string = "foo"

很显然,使用这种语法,x -> "foo"情况包含所有内容.有没有办法使其等同于:

Obviously, with this syntax, the x -> "foo" case takes everything. Is there a way to make it be equivalent to:

match 2 with
| 2 -> "foo"
| 5 -> "bar"
| _ -> "baz"

匹配表达式的值是在运行时确定的?

where the values of the match expressions are determined at runtime?

推荐答案

您需要when保护:

let x = 2 in
let y = 5 in
match 2 with
| z when z = x -> "foo"
| z when z = y -> "bar"
| _ -> "baz";;

错误消息很有启发性.使用时:

The error messages are very instructive. When you use:

let x = 2 in
...
match 2 with
| x -> "foo"
| ...

新值x在上一个让步边界中遮盖了值x,因此是第一条错误消息.此外,由于新的x匹配所有内容,因此y_的以下两个模式显然是多余的.

the new value x shadows the value x in previous let-bound hence the first error message. Moreover, since the new x matches everything, two below patterns of y and _ are obviously redundant.

请注意,匹配常数(match 2 with)并不是一个好主意.

Note that matching a constant (match 2 with) is not a good idea.

这篇关于OCaml模式与非常量匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆