中缀运算符的 Scala 匹配分解

发布于 2024-07-25 00:17:11 字数 304 浏览 4 评论 0原文

我试图了解 Scala 中 List 的实现。 特别是,我试图了解如何使用中缀运算符编写匹配表达式,例如:

a match {
  case Nil => "An empty list"
  case x :: Nil => "A list without a tail"
  case x :: xs => "A list with a tail"
}

如何允许匹配表达式为 x :: xs 而不是 List (x,xs)?

I'm trying to understand the implementation of Lists in Scala. In particular I'm trying to get my head around how you can write match expressions using an infix operator, for example:

a match {
  case Nil => "An empty list"
  case x :: Nil => "A list without a tail"
  case x :: xs => "A list with a tail"
}

How is the match expression allowed to be x :: xs rather than List(x, xs)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

因为看清所以看轻 2024-08-01 00:17:11

杰伊·康拉德的回答几乎是正确的。 重要的是,某处有一个名为 :: 的对象,它实现了 unapply 方法,返回类型 Option[(A,列表[A])]。 因此:

object :: {
  def unapply[A](ls: List[A]): Option[(A, A)] = {
    if (ls.empty) None
    else Some((ls.head, ls.tail))
  }
}

// case objects get unapply for free
case object Nil extends List[Nothing]

::List 的情况下,该对象恰好来自 :: 是一个扩展了的 case 类List 特征。 然而,如上面的示例所示,它根本不是一个案例类。

Jay Conrad's answer is almost right. The important thing is that somewhere there is an object named :: which implements the unapply method, returning type Option[(A, List[A])]. Thusly:

object :: {
  def unapply[A](ls: List[A]): Option[(A, A)] = {
    if (ls.empty) None
    else Some((ls.head, ls.tail))
  }
}

// case objects get unapply for free
case object Nil extends List[Nothing]

In the case of :: and List, this object happens to come out of the fact that :: is a case class which extends the List trait. However, as the above example shows, it doesn't have to be a case class at all.

三生殊途 2024-08-01 00:17:11

我相信 :: 实际上是一个类(它是 List 的子类),所以x :: xs 基本上等同于 List(x, xs)

您可以对具有运算符名称的其他案例类执行此操作。 例如:

case class %%%(x: Int, y: Int)

a match {
  case x %%% y => x + y
}

I believe :: is actually a class (which is a subclass of List), so saying x :: xs is mostly equivalent to List(x, xs).

You can do this with other case classes that have operator names. For instance:

case class %%%(x: Int, y: Int)

a match {
  case x %%% y => x + y
}
送君千里 2024-08-01 00:17:11

如何允许匹配表达式为 x :: xs 而不是 List(x, xs)?

回答这个问题:

当被视为模式时,中缀
p op q 等操作是等效的
op(p, q)。 也就是说,中缀
运算符 op 被视为
构造函数模式

(Scala 编程,第一版,第 331 页)

另请参阅 scala 案例类问题

How is the match expression allowed to be x :: xs rather than List(x, xs)?

To answer this question:

When seen as a pattern, an infix
operation such as p op q is equivalent
to op(p, q). That is, the infix
operator op is treated as a
constructor pattern.

(Programming in Scala, 1st ed., p. 331)

See also scala case classes questions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文