Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Created October 31, 2013 10:44
Show Gist options
  • Select an option

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

Select an option

Save hanbzu/7247683 to your computer and use it in GitHub Desktop.
Scala: Collections, more: Vectors, Ranges, exists, forall, zip, unzip, etc.
// Vectors, externally, are similar to Lists
val nums = Vector(1, 2, 3, -88)
// But instead of :: we use:
9 +: nums // Vector(9, 1, 2, 3, -88)
nums :+ 9 // Vector(1, 2, 3, -88, 9) -- : always points to the sequence
// Arrays and String support the same ops as Seq,
// but are not a Seq (because they come from Java),
// but can be converted to a Seq
val xs: Array[Int] = Array(1, 2, 3)
xs map (2 * _) // Array(2, 4, 6)
val ys: String = "Hello World!"
ys filter (_.isUpper) // "HW"
// Ranges
val r: Range = 1 until 5 // 1, 2, 3, 4
val s: Range = 1 to 5 // 1, 2, 3, 4, 5
1 to 10 by 3 // 1, 4, 7, 10
6 to 1 by -2 // 6, 4, 2
// Operations that exist for all sequences
xs exists p // true if there an element of xs such that p(x) holds
xs forall p // true if all the elements of xs hold
xs zip ys // Creates sequence pairs (x1, y1), (x2, y2) ...
xs.unzip // Unzips a pair sequence into two sequences
xs.flatMap f // map with f and concatenate result
xs.sum
xs.product
xs.max
xs.min
// EXAMPLE: All combinations of numbers where x
// is drawn from 1..M and y is drawn from 1..N
(1 to M) flatMap (x => (1 to N) map (y => (x, y)))
// EXAMPLE: Scalar product
(xs zip ys).map{ case(x, y) = x * y }.sum
// In case it's strange to see case like that:
{ case p1 => e1 ... case pn => en }
// is equivalent to
x => x match { case p1 => e1 ... case pn => en }
// EXAMPLE: Is prime?
def isPrime(n: Int): Boolean = (2 until n) forall (d => n % d != 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment