Scalaで私の最初のステップを踏んで、私は最初の誤解に遭遇しました。
リンクリストの古典的な例を取り上げました。Scalaリンクリスト
sealed trait List[+A] // `List` data type, parameterized on a type, `A`
case object Nil extends List[Nothing] // A `List` data constructor representing the empty list
/* Another data constructor, representing nonempty lists. Note that `tail` is another `List[A]`,
which may be `Nil` or another `Cons`.
*/
case class Cons[+A](head: A, tail: List[A]) extends List[A]
object List { // `List` companion object. Contains functions for creating and working with lists.
def sum(ints: List[Int]): Int = ints match { // A function that uses pattern matching to add up a list of integers
case Nil => 0 // The sum of the empty list is 0.
case Cons(x,xs) => x + sum(xs) // The sum of a list starting with `x` is `x` plus the sum of the rest of the list.
}
def product(ds: List[Double]): Double = ds match {
case Nil => 1.0
case Cons(0.0, _) => 0.0
case Cons(x,xs) => x * product(xs)
}
def apply[A](as: A*): List[A] = // Variadic function syntax
if (as.isEmpty) Nil
else Cons(as.head, apply(as.tail: _*))
val x = List(1,2,3,4,5) match {
case Cons(x, Cons(2, Cons(4, _))) => x
case Nil => 42
case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y
case Cons(h, t) => h + sum(t)
case _ => 101
}
}
いくつかの質問があります。
1)コードの一部は、私たちがしているときに正しいことになっている理由は、カスタムリンクListクラス)が内蔵されscala.collection.immutable.List.type
2と競合していない理由は、組み込みリストをカスタムリンクリストにマッチングさせますか?
val x = List(1,2,3,4,5) match {
case Cons(x, Cons(2, Cons(4, _))) => x
case Nil => 42
case Cons(x, Cons(y, Cons(3, Cons(4, _)))) => x + y
case Cons(h, t) => h + sum(t)
case _ => 101
}
返信いただきありがとうございます。しかし、どのように建設リスト(1、2、3、4、5)を使用することが可能ですか?そのような機会を与えるメソッドを適用しますか? –
'List'オブジェクトの' apply [A](as:A *):List [A] 'メソッドを呼び出しています。 –