pattern-matching - 匹配变量(或以其他方式引入匹配逻辑的抽象)

标签 pattern-matching ocaml ml

可以匹配文字(显然):

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 语言中的 ifswitch 的权衡。如果您想与编译时已知的一组值进行比较,switch 的效率要高得多。但它不会尝试成为通用的 if

关于pattern-matching - 匹配变量(或以其他方式引入匹配逻辑的抽象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47782225/

相关文章:

scala - Scala 中的模式匹配元组

sql - 在第一次出现字符后剪切字符串

PHP删除字符串中的重复模式

module - 通过命令行参数选择要使用的 ocaml 模块

sml - 在函数 - SML 中列出数字 1 到 n

Python 在大量数字中寻找模式?

module - OCaml 模块中的私有(private)值?

ocaml - 创建一个简单的 camlp4 语法扩展

在 OCaml 函数的 C 实现中创建求和类型

haskell - 如何定义该函数的类型配置文件?