可以匹配文字(显然):
let res = match x with
| "abc" -> 1
| "def" as x -> something_else x
问:但是,是否有可能匹配变量的值,这样文字就不会在整个代码中重复?
let abc = "abc"
let def = "def"
let res = match x with
| (abc) -> 1
...
(以上当然不会匹配 abc
,但会匹配所有情况)
在 F# 中,可以使用事件模式:
let (|IsAbc|IsDef|) str = if str = abc then IsAbc(str)
else if str = def then IsDef(str)
...
let res = match x with
| IsAbc x -> 1
| IsDef x -> somethingElse x
这允许抽象匹配逻辑并只定义一次文字。我怎样才能在 OCaml 中实现这一点?
我得到的最接近的是:但是感觉有点笨拙?
let is_abc str = str = abc
let is_def str = str = def
...
let res = match x with
| x when is_abc x -> 1
| x when is_def x -> something_else x
或者使用if
:但是它看起来不如match
优雅(另外,要匹配y
,必须进行 n 次编辑,而使用 match
时为 1 次)
let res = if x = abc then 1
else if x = def then something_else x
最佳答案
使用 when
本质上是您在 OCaml 中可以做的最好的事情。我认为它看起来并不比您提供的 F# 等价物笨拙。但这也许是一个品味问题。
您也可以分解并使用 if
表达式。这就是我个人会做的。我看不出假装 OCaml match
比实际更通用有什么好处。
您可能会认为它类似于类 C 语言中的 if
和 switch
的权衡。如果您想与编译时已知的一组值进行比较,switch
的效率要高得多。但它不会尝试成为通用的 if
。
关于pattern-matching - 匹配变量(或以其他方式引入匹配逻辑的抽象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47782225/