Skip to content

Instantly share code, notes, and snippets.

@taitruong
Created April 1, 2014 13:29
Show Gist options
  • Save taitruong/9913977 to your computer and use it in GitHub Desktop.
Save taitruong/9913977 to your computer and use it in GitHub Desktop.
list operations, higher-order methods: filter, partition, takeWhile, dropWhile, and span
object ScalaHackSession {
//filter all even numbers
val list = (1 to 10).toList //> list : List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
list.filter(_ % 2 == 0) //> res0: List[Int] = List(2, 4, 6, 8, 10)
//find is like filter but stops after the first true condition
val result = list.find(element => element > 3 && element % 3 == 0)
//> result : Option[Int] = Some(6)
result match {
case Some(element) => println(element + ": found")
case None => println("Not in list")
} //> 6: found
//partition where first list fulfills predicate and remainin is in second list
list.partition(element => element > 3 && element % 3 == 0)
//> res1: (List[Int], List[Int]) = (List(6, 9),List(1, 2, 3, 4, 5, 7, 8, 10))
//take all elements while predicate is true
list.takeWhile(_ < 6) //> res2: List[Int] = List(1, 2, 3, 4, 5)
//drop all elements while predicate is true
list.dropWhile(_ < 6) //> res3: List[Int] = List(6, 7, 8, 9, 10)
//span a combination of takeWhile and dropWhile
list.span(_ < 6) //> res4: (List[Int], List[Int]) = (List(1, 2, 3, 4, 5),List(6, 7, 8, 9, 10))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment