Scalaでパターンマッチングがどのように機能するかを(一種で)理解しています。次の形式のリストが2つあるとしましょう。
sealed abstract class IntList
case class Empty() extends IntList // The empty list, often called Nils
case class Element(n: Int, tail: IntList) extends IntList // Element is usually called Cons
関数を作成したいとしましょう take(n, xs)
通常のパターンマッチングで試しました:
def take(n: Int, xs: IntList): IntList = xs match {
case n == 0 => Empty()
case xs : Empty => Empty()
case xs : Element => Element(xs.n, take(n-1, xs))
}
しかし、もちろん、nは認識されません。 error: not found: value == case n == 0 => Empty()
どうすればこれを行うことができますか、それはおそらく簡単ですが、私はScalaの初心者ですか?
最初のケースでタイプミスがあります。
case _ if n == 0 => Empty()
そして、あなたが合格するのを忘れた3番目のケースのバグ tail
case xs: Element => Element(xs.n, take(n-1, xs.tail))
試してみてください
sealed trait IntList
case object Empty extends IntList
case class Element(n: Int, tail: IntList) extends IntList
def take(n: Int, xs: IntList): IntList = xs match {
case _ if n == 0 => Empty
case Empty => Empty
case Element(n, tail) => Element(n, take(n-1, tail))
}
val list = Element(1, Element(2, Element(3, Empty)))
take(2, list) // res0: IntList = Element(1,Element(2,Empty))
検討case object
の代わりcase class Empty()
に従ってデータがない場合、ケースオブジェクトTとケースクラスT()を定義ADTの違い?
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加