Last active
October 14, 2015 17:52
-
-
Save fernandomora/102a3837b283e439278c to your computer and use it in GitHub Desktop.
Scala Monad sequence method for generic travesables using for-comprehensions and builder pattern
This file contains 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
import scala.language.higherKinds | |
def sequence[A, M[X] <: TraversableOnce[X]](in: M[Monad[A]])(implicit cbf: CanBuildFrom[M[Monad[A]], A, M[A]]): Monad[M[A]] = { | |
val unit = Monad(cbf(in)) | |
in.foldLeft(unit){ | |
(mba, ma) => for (ba <- mba; a <- ma) yield ba += a | |
}.map(_.result()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment