0

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)

}

なんで?

4

1 に答える 1

2

コンストラクターの引数は、クラス内でのみ表示されます。フィールドにしたい場合は、次のように言う必要があります。

class Succ(val x: Nat) extends Nat { … }
//         ^^^
于 2014-08-19T14:53:47.830 に答える