Created
October 31, 2013 07:32
-
-
Save hanbzu/7245597 to your computer and use it in GitHub Desktop.
Scala: map operation. Didactic.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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