模式匹配OCaml中的变量? [英] Pattern matching a variable in OCaml?

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

问题描述

如果我愿意

let check n = function
  | n -> true
  | _ -> false

然后我得到Warning 11: this match case is unused.

我理解为什么,因为 |中的n n-> true 实际上不是check的参数.它基本上是由模式匹配创建的变量.

I understand why, since the n in | n -> true is actually not the argument of check. It is basically a variable created by the pattern matching.

我的问题是,在这种情况下,我们是否仍然可以使用模式匹配(而不是其他方式)来强制执行此检查?

My question is, in this case, do we have any way to still using pattern matching (instead of if else) to force this check?

即,我想与参数n进行模式匹配.

I.e., I want to pattern match with the argument n.

推荐答案

您可以使用when将模式与布尔条件一起使用:

You can use when to have patterns along with boolean conditions:

let check n = function
| x when x = n -> true
| _ -> false

但是,这不是很特别:使用if只是语法不同.

However, this isn't very special: it's just different syntax for using an if.

OCaml不支持任何与变量的 value 匹配的动态"模式-模式都是静态的.有一种名为 bondi 的研究语言,它确实支持这种动态模式.它与OCaml非常相似,因此,如果您对这种功能感兴趣,就应该试用一下.

OCaml does not support any sort of "dynamic" pattern that lets you match against the value of a variable--patterns are all static. There is a research language called bondi which does support dynamic patterns like this. It's quite similar to OCaml, so if you're interested in this sort of feature you should play around with it.

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

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