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

No comments:

Post a Comment