Naturals の scala での定義と、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)
}
なんで?