我只是在 scala 中为 Naturals 创建了一个定义,还有一个 PLUS 操作:
abstract class Nat {
def +(other:Nat):Nat = this match {
case Zero => other
case Succ(x) => x + Succ(other)
}
}
object Zero extends Nat {
override def toString = "Zero"
}
对于 Succ 的定义,出于学习目的,我尽量不使用 Case 类。我的第一种方法是:
class Succ(x: Nat) extends Nat {
override def toString = "Succ(" + x.toString + ")"
}
object Succ {
def apply(x: Nat) = new Succ(x)
def unapply(s: Succ) = Some(s.x)
}
但是编译器给我一个错误
Error:( , ) value x is not a member of Succ
def unapply(s: Succ) = Some(s.x)
^
我为获取 X 做了一个明确的方法,它可以工作
class Succ(x: Nat) extends Nat {
def getX = x
override def toString = "Succ(" + x.toString + ")"
}
object Succ {
def apply(x: Nat) = new Succ(x)
def unapply(s: Succ) = Some(s.getX)
}
为什么?