Showing posts with label b1107| Nil. Show all posts
Showing posts with label b1107| Nil. Show all posts

Pattern Matching on Sequence

scala> //PS:104
//convertToStr() : Method that takes a type parameter to convert a Sequence to String
scala> def convertToStr[T](seq: Seq[T]):String = {
     |     seq match {
     |         // Note 1 : Although a Sequence has 'head' & 'tail' methods
     |         //          here 'head' & 'tail' are considered as variable names
     |         // Note 2 : '+:' is called as 'cons'(Construction) Operator
     |         case head +: tail => s"$head +: " + convertToStr(tail)
     |
     |         // Nil is a Special Object that represents an Empty Sequence
     |         case Nil => "Nil"
     |     }
     | }
convertToStr: [T](seq: Seq[T])String

scala>

scala> val seq1 = Seq('a', 'b', 'c')
seq1: Seq[Char] = List(a, b, c)

scala> val seq2 = Seq.empty[Char]
seq2: Seq[Char] = List()

scala> val ls1 = List('d', 'e', 'f')
ls1: List[Char] = List(d, e, f)

scala> val ls2 = List.empty[Char]
ls2: List[Char] = List()

scala>

scala> for (seq <- Seq(seq1, seq2, ls1, ls2)) {
     |     println(convertToStr(seq))
     | }
a +: b +: c +: Nil
Nil
d +: e +: f +: Nil
Nil

Ways to create a Sequence

Seq is the parent type of all Concrete collections(List, Vector etc...) that support Iteration. Nil represents an Empty List
scala> val seq1 = Seq(1, 2)
//PS:104, 107
seq1: Seq[Int] = List(1, 2)

scala> val seq2 = (1 +: (2 +: (Nil)))
seq2: List[Int] = List(1, 2)

scala> val seq3 = (1 :: (2 :: (Nil)))
seq3: List[Int] = List(1, 2)