Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Last active December 27, 2015 00:09
Show Gist options
  • Select an option

  • Save hanbzu/7235804 to your computer and use it in GitHub Desktop.

Select an option

Save hanbzu/7235804 to your computer and use it in GitHub Desktop.
Scala: Lists
// Scala lists
val xs = "Apple" :: "Mango" :: "Watermelon" :: Nil
xs.length // 3
xs.head // "Apple"
xs.last // "Watermelon"
xs.init // All except last one: List("Apple", "Mango") -- Slower than tail!!
xs.tail // All except first one: List("Mango", "Watermelon") -- Slower than head!!
xs take 2 // It takes the first 2 elements. List("Apple", "Mango")
xs drop 2 // The rest after taking two: List("Watermelon")
xs(2) // xs apply 2 -- Element at position 2: List("Watermelon")
// Creating new lists
xs ++ ys // Concatenate, also xs ::: ys (only for lists)
xs.reverse // Elements in reversed order
xs updated (n, x) // All elements are the same except the one at n, updated to x
// Finding elements
xs indexOf x // Index of the first elem equal to x, or -1 if it's not there
xs contains x // xs indexOf x >= 0
// Example1: Remove element at position n
def removeAt(n: Int, xs: List[Int]) = (xs take n) ::: (xs drop n)
// Example2: Flatten:
// flatten(List(List(1, 1), 2, List(3, List(5, 8))))
// res0: List[Any] = List(1, 1, 2, 3, 5, 8)
def flatten(xs: List[Any]): List[Any] = xs match {
case Nil => Nil
case (y: List[_]) :: ys => flatten(y) ++ flatten(ys)
case y :: ys => y :: flatten(ys)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment