Skip to content

Instantly share code, notes, and snippets.

@awilmore
Created May 22, 2012 11:39
Show Gist options
  • Save awilmore/2768526 to your computer and use it in GitHub Desktop.
Save awilmore/2768526 to your computer and use it in GitHub Desktop.
Various Scala Examples
// Find character with largest Unicode value
"Hello".reduceLeft((x, y) => if(x > y) x else y)
// Sum the unicode numeric value of the characters in "Hello World"
println("Hello World".foldLeft(0)((x, y) => x + y))
// Filter characters with even Unicode values
"Hello".filter(c => c % 2 == 0) // Filter characters with even Unicode values
"Hello".filter(_ % 2 == 0)
// Stream example
val s = Stream.from(1).takeWhile(_ > 0)
s.takeWhile(_ < 10).toList
s.takeWhile(_ < 10).mkString
// Prepend to a stream
val t = 0 #:: s
t.takeWhile(_ < 10).mkString
// Concatenating Lists
List(1, 2, 3) ++ List(4, 5, 6)
List(1, 2, 3) ::: List(4, 5, 6) // Possibly deprecated
// Example of zip function
List(1, 2, 3).zip(List(4, 5, 6))
// Examples of map function
(1 until 10).map(num => "file" + num)
(1 to 10).map { x => (x, x * x) }
// Convert List of tuples to Map
(1 to 10).map { x => (x, x * x) }.toMap
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment