summaryrefslogtreecommitdiffstats
path: root/Scala/sandbox/11-pack.scala
blob: d593efdf8c1b323e00b2a77ea8612536eeedda18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
object Pack
{

  def pack[T](xs: List[T]): List[List[T]] = xs match {
    case Nil      => Nil
    case x :: xs1 =>
    val (first, last) = xs span(y => y == x) // takeWhile + dropWhile
    first :: pack(last)
  }

  def encode[T](xs: List[T]): List[(T,Int)] = pack(xs) map (ys => (ys.head, ys.length))

  def run = {
    println("Pack")
    val l = List("a", "a", "a", "b", "c", "c", "a")
    println(pack(l))
    println(encode(l))
  }
}