Skip to content

Instantly share code, notes, and snippets.

View andrewharmellaw's full-sized avatar

Andrew Harmel-Law andrewharmellaw

View GitHub Profile
@andrewharmellaw
andrewharmellaw / AboutTuples.scala
Last active December 17, 2015 13:09
Explicit Tuple Creation
koan("Tuples can be created easily") {
val tuple = ("apple", "dog")
tuple should be(Tuple2("apple", "dog"))
}
@andrewharmellaw
andrewharmellaw / AboutTuples.scala
Created May 20, 2013 19:26
More Tuple Literals
koan("Tuples can be created easily") {
val tuple = ("apple", "dog")
tuple should be("apple", "dog")
}
@andrewharmellaw
andrewharmellaw / AboutLists.scala
Created May 21, 2013 19:14
FilterNot - Funny Names
val b = a.filterNot(v => v == 5) // remove where value is 5
// map a function to double the numbers over the list
a.map {v => v * 2} should equal(List(__, __, __, __, __))
@andrewharmellaw
andrewharmellaw / AboutLists.scala
Created May 21, 2013 19:23
reduceLeft syntax
koan("Lists can be 'reduced' with a mathematical operation") {
val a = List(1, 3, 5, 7)
// note the two _s below indicate the first and second args respectively
a.reduceLeft(_ + _) should equal(16) // 1 + 3 + 5 + 7
a.reduceLeft(_ * _) should equal(105) // 1 * 3 * 5 * 7
}
koan("Foldleft is like reduce, but with an explicit starting value") {
val a = List(1, 3, 5, 7)
// NOTE: foldLeft uses a form called currying that we will explore later
a.foldLeft(0)(_ + _) should equal(16)
a.foldLeft(10)(_ + _) should equal(26)
a.foldLeft(1)(_ * _) should equal(105)
a.foldLeft(0)(_ * _) should equal(0)
}
@andrewharmellaw
andrewharmellaw / RangeLiteral.scala
Created May 21, 2013 19:49
Nice Range literal syntax
val a = (1 to 5).toList
koan("Lists reuse their tails") {
val d = Nil
val c = 3 :: d
val b = 2 :: c
val a = 1 :: b
a should be(List(1, 2, 3))
a.tail should be(b)
b.tail should be(c)
c.tail should be(d)
@andrewharmellaw
andrewharmellaw / AboutMaps.scala
Created May 28, 2013 07:29
Map.values() returns an Iterable
// NOTE that the following will not compile, as iterators do not implement "contains"
// mapValues.contains("Illinois") should be (true)
@andrewharmellaw
andrewharmellaw / AboutMaps.scala
Created May 28, 2013 07:30
Map.values() from the REPL
scala> val myMap = Map("MI" -> "Michigan", "OH" -> "Ohio", "WI" -> "Wisconsin", "MI" -> "Michigan")
myMap: scala.collection.immutable.Map[java.lang.String,java.lang.String] = Map(MI -> Michigan, OH -> Ohio, WI -> Wisconsin)
scala> val mapValues = myMap.values
mapValues: Iterable[java.lang.String] = MapLike(Michigan, Ohio, Wisconsin)