Skip to content

Instantly share code, notes, and snippets.

@bmjames
Created March 20, 2014 17:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmjames/9669467 to your computer and use it in GitHub Desktop.
Save bmjames/9669467 to your computer and use it in GitHub Desktop.
Comparing Scala's List#map to Haskell's map
-- http://hackage.haskell.org/package/base-4.6.0.1/docs/src/GHC-Base.html#map
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
// https://github.com/scala/scala/blob/c5962b1871f8093fe200fe0c47cd9c202b07a8f9/src/library/scala/collection/immutable/List.scala#L270-L287
@noinline // TODO - fix optimizer bug that requires noinline (see SI-8334)
final override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[List[A], B, That]): That = {
if (bf eq List.ReusableCBF) {
if (this eq Nil) Nil.asInstanceOf[That] else {
val h = new ::[B](f(head), Nil)
var t: ::[B] = h
var rest = tail
while (rest ne Nil) {
val nx = new ::(f(rest.head), Nil)
t.tl = nx
t = nx
rest = rest.tail
}
h.asInstanceOf[That]
}
}
else super.map(f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment