Skip to content

Instantly share code, notes, and snippets.

@berdario berdario/fold.scala
Created Oct 19, 2014

Embed
What would you like to do?
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
You can’t perform that action at this time.