解释这个模式匹配代码 [英] Explain this pattern matching code

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

问题描述

此代码来自使用 Scala 的模式匹配查询数据集:

This code is from Querying a Dataset with Scala's Pattern Matching:

object & { def unapply[A](a: A) = Some((a, a)) }

"Julie" match {
  case Brothers(_) & Sisters(_) => "Julie has both brother(s) and sister(s)"
  case Siblings(_) => "Julie's siblings are all the same sex"
  case _ => "Julie has no siblings"
}

// => "Julie has both brother(s) and sister(s)"

& 实际上是如何工作的?我在任何地方都没有看到有关合取的布尔测试.这个 Scala 魔法是如何工作的?

How does & actually work? I don't see a Boolean test anywhere for the conjunction. How does this Scala magic work?

推荐答案

以下是 unapply 的一般工作原理:

Here's how unapply works in general:

当你这样做

obj match {case Pattern(foo, bar) => ... }

Pattern.unapply(obj) 被调用.这可以返回 None 在这种情况下模式匹配失败,或者 Some(x,y) 在这种情况下 foobar 绑定到 xy.

Pattern.unapply(obj) is called. This can either return None in which case the pattern match is a failure, or Some(x,y) in which case foo and bar are bound to x and y.

如果你使用 Pattern(OtherPattern, YetAnotherPatter) 而不是 Pattern(foo, bar),那么 x 将与模式匹配 OtherPatterny 将与 YetAnotherPattern 匹配.如果所有这些模式匹配成功,则执行匹配的主体,否则尝试下一个模式.

If instead of Pattern(foo, bar) you did Pattern(OtherPattern, YetAnotherPatter) then x would be matched against the pattern OtherPattern and y would be matched against YetAnotherPattern. If all of those pattern matches are successful, the body of the match executes, otherwise the next pattern is tried.

当一个模式的名称不是字母数字而是一个符号(如 &)时,它被用作中缀,即你写 foo &bar 而不是 &(foo, bar).

when the name of a pattern is not alphanumeric, but a symbol (like &), it is used infix, i.e. you write foo & bar instead of &(foo, bar).

所以这里的 & 是一个总是返回 Some(a,a) 的模式,不管 a 是什么.所以 & 总是匹配并将匹配的对象绑定到它的两个操作数.在代码中,这意味着

So here & is a pattern that always returns Some(a,a) no matter what a is. So & always matches and binds the matched object to its two operands. In code that means that

obj match {case x & y => ...}

将始终匹配并且 xy 将与 obj 具有相同的值.

will always match and both x and y will have the same value as obj.

在上面的示例中,这用于将两种不同的模式应用于同一对象.

In the example above this is used to apply two different patterns to the same object.

即当你这样做

obj match { case SomePattern & SomeOtherPattern => ...}`

首先应用模式 &.正如我所说,它总是匹配并绑定 obj 到它的 LHS 和它的 RHS.那么将 SomePattern 应用于 & 的 LHS(与 obj 相同)并且 SomeOtherPattern 是应用于 & 的 RHS(也与 obj 相同).

first the pattern & is applied. As I said, it always matches and binds obj to its LHS and its RHS. So then SomePattern is applied to &'s LHS (which is the same as obj) and SomeOtherPattern is applied to &'s RHS (which is also the same as obj).

因此,实际上,您只是将两种模式应用于同一个对象.

So in effect, you just applied two patterns to the same object.

这篇关于解释这个模式匹配代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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