gpt4 book ai didi

Scala Constructor 模式与 Extractor 模式匹配

转载 作者:行者123 更新时间:2023-12-04 17:52:37 24 4
gpt4 key购买 nike

构造器模式和抽取器模式匹配有什么区别?在 Programming in Scala 中,作者区分了第 15 章中讨论的构造函数模式和第 26 章中讨论的提取器模式。

构造函数模式的例子:

abstract class Expr
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr

expr match {
case BinOp("+", e, Number(0)) => println("a deep match")
case _ =>
}

提取器示例:

l match {
case List(a,b,c) => a
case _ =>
}

最佳答案

区别在规范中表示:

An extractor pattern x(p1, …, pn) where n ≥ 0 is of the same syntactic form as a constructor pattern. However, instead of a case class, the stable identifier x denotes an object which has a member method named unapply or unapplySeq that matches the pattern.

简单地说,构造函数模式讨论案例类的分解,其中提取器模式讨论任何具有 unapplyunapplySeq 的对象。

List[A] 有一个 unapplySeq 由抽象 SeqFactory 提供:

/** This method is called in a pattern match { case Seq(...) => }.
*
* @param x the selector value
* @return sequence wrapped in an option, if this is a Seq, otherwise none
*/
def unapplySeq[A](x: CC[A]): Some[CC[A]] = Some(x)

关于Scala Constructor 模式与 Extractor 模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42622811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com