Thursday, October 13, 2016

List Methods : reverse, splitAt(), take(), drop()

scala> // All this methods are first order methods

scala> // (ie methods that do not take function as an argument)

scala>

scala> // reverse : Reverse a list #350

scala> val wxyz = List("w", "x", "y", "z")
wxyz: List[String] = List(w, x, y, z)

scala> val res = wxyz.reverse
res: List[String] = List(z, y, x, w)

scala>

scala> // splitAt() :  Splits the list at a given index

scala> //              returning pair of lists #350

scala> val data = List("a", "b", "c", "d", "e", "f")
data: List[String] = List(a, b, c, d, e, f)

scala> val res = data.splitAt(2)
res: (List[String], List[String]) = (List(a, b),List(c, d, e, f))

scala>

scala> // take() : Take N no of elements from a list

scala> val data = List("a", "b", "c", "d", "e", "f")
data: List[String] = List(a, b, c, d, e, f)

scala> val res = data.take(2)
res: List[String] = List(a, b)

scala>

scala> // drop() : Drop the first N elements from the list

scala> val data = List("a", "b", "c", "d", "e", "f")
data: List[String] = List(a, b, c, d, e, f)

scala> val res = data.drop(2)
res: List[String] = List(c, d, e, f)