简体   繁体   English

OCaml相当于Haskell的@in模式匹配(又称as-pattern)

[英]OCaml equivalent to Haskell's @ in pattern matching (a.k.a. as-pattern)

In Haskell, while pattern matching, I can use @ to get the entire structure in a pattern. 在Haskell中,在模式匹配时,我可以使用@来获取模式中的整个结构。 (For easier Googling, this structure is known as an as-pattern.) (为了便于谷歌搜索,这种结构称为as-pattern。)

For example, x:xs decomposes a list into a head and a tail; 例如, x:xs将列表分解为头部和尾部; I can also get the entire list with xxs@(x:xs) . 我也可以使用xxs@(x:xs)获取整个列表。

Does OCaml have something like this? OCaml有这样的东西吗?

You can use as : 您可以使用as

let f = function
| [] -> (* ... *)
| (x::xs) as l ->
  (*
   here:
   - x is the head
   - xs is the tail
   - l is the whole list
  *)

Let me extend Etienne's answer a little bit with some examples: 让我用一些例子来扩展艾蒂安的答案:

let x :: xs as list = [1;2;3];;
val x : int = 1
val xs : int list = [2; 3]
val list : int list = [1; 2; 3]

When you write <pattern> as <name> , the variable <name> is bound to the whole pattern on the left, in other words, the scope of as extends as far to the left as possible (speaking more techically as has lower priority than constructors, ie, the constructors bind tighter). 当您将<pattern> as <name><pattern> as <name> ,变量<name>绑定到左侧的整个模式,换句话说, as范围尽可能向左延伸(更具技术性, as优先级较低)比构造函数,即构造函数绑定更严格)。 So, in case of the deep pattern matching, you might need to use parentheses to limit the scope, eg, 因此,在深度模式匹配的情况下,您可能需要使用括号来限制范围,例如,

let [x;y] as fst :: ([z] as snd) :: xs as list = [[1;2];[3]; [4]];;
val x : int = 1
val y : int = 2
val fst : int list = [1; 2]
val z : int = 3
val snd : int list = [3]
val xs : int list list = [[4]]
val list : int list list = [[1; 2]; [3]; [4]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM