Skip to content

Instantly share code, notes, and snippets.

@berdario
Created October 19, 2014 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berdario/1aa5f6c36bb4d23512c4 to your computer and use it in GitHub Desktop.
Save berdario/1aa5f6c36bb4d23512c4 to your computer and use it in GitHub Desktop.
import scala.language.higherKinds
import scala.collection.generic.CanBuildFrom
import scala.collection.GenTraversableOnce
def map[A, This[A] <: Traversable[A], B, That](o: This[A])(f: (A) => B)(implicit bf: CanBuildFrom[This[A], B, That]): That = {
(o.foldLeft (bf.apply()) ({(a, b) => a += f(b)})).result()
}
def filter[A, This[A] <: Traversable[A]](o: This[A])(f: (A) => Boolean)(implicit bf: CanBuildFrom[This[A], A, This[A]]): This[A] = {
(o.foldLeft (bf.apply()) ({(a, b) => if (f(b)) a += b else a})).result()
}
def flatMap[A, This[A] <: Traversable[A], B, That](o: This[A])(f: (A) => GenTraversableOnce[B])(implicit bf: CanBuildFrom[This[A], B, That]): That = {
(o.foldLeft (bf.apply()) ({(a, b) => f(b).foldLeft (a) (_ += _)})).result()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment