Skip to content

Instantly share code, notes, and snippets.

@hanbzu
Created October 31, 2013 07:32
Show Gist options
  • Select an option

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

Select an option

Save hanbzu/7245597 to your computer and use it in GitHub Desktop.
Scala: map operation. Didactic.
// An operation for each of the elements in a list
def scaleList(xs: List[Double], factor: Double) = xs match {
case Nil => xs
case y :: ys => y * factor :: scaleList(ys, factor)
}
// A simple way to define map
// In reality it's more complicated because:
// * It works for arbitrary collections, not only lists
// * Its tail recursive
abstract class List[T] { ...
def map[U](f: T => U): List[U] = this match {
case Nil => this
case x :: xs => f(x) :: xs.map(f)
}
}
// Back to scaleList
def scaleList(xs: List[Double], factor: Double) = xs.map(x => x * factor)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment