Created
January 19, 2015 03:00
-
-
Save r-wheeler/6075bf87237f67222322 to your computer and use it in GitHub Desktop.
99 Scala (problems 8 - 12) answers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//p08 | |
def compress[A](xs: List[A]): List[A] = | |
xs match { | |
case x :: xs if (!xs.contains(x)) => x :: compress(xs) | |
case x :: xs => compress(xs) | |
case Nil => Nil | |
} | |
def compress2[A](xs: List[A]): List[A] = { | |
xs.foldRight(List.empty[A]){ | |
case (x,acc) => if (!acc.contains(x)) x :: acc else acc | |
} | |
} | |
// | |
val myList = "aaabbcccccd" toList | |
//p09 | |
def pack[A](l:List[A]): List[List[A]] = { | |
l match { | |
case x :: xs => | |
xs.foldLeft(List(List(x))){ | |
case (z,a) => | |
if (z.head.head == a) | |
(a +: z.head) +: z.tail | |
else | |
List(a) +: z | |
}.reverse | |
case _ => Nil | |
} | |
} | |
pack(myList) | |
//p10 | |
def encode[A](xs: List[A]): List[(Int,A)] = | |
pack(xs) map {x => (x.size,x.head) } | |
encode(myList) | |
//p11 | |
def encodeModified[A](xs: List[A]): List[Any] = | |
encode(xs) map {x => if (x._1 ==1) x._2 else x} | |
encodeModified(myList) | |
//p12 | |
def decode[A](ls: List[(Int,A)]): List[A] = | |
ls flatMap {x => List.fill(x._1)(x._2)} | |
decode(encode(myList)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment