Adding foldM to Monad and a test #136

merged 2 commits into from Mar 12, 2013


None yet

2 participants

ccsevers commented Mar 8, 2013

Pretty small change but it could be nice to have.

It's implemented in terms of flatMap and apply so it should work with everything. I made the list part GenTraversable since I don't see a nice way to do it with GenTraversableOnce.

johnynek commented Mar 8, 2013

Like this (and adding more combinators on Monads), but can we add them to object Monad and not to the Monad class?

The reason is, foldM should never be overridden and is only a function of flatMap/apply. So, would you be willing to move your logic to the companion object?

@johnynek johnynek commented on an outdated diff Mar 8, 2013
@@ -48,6 +56,8 @@ object Monad {
def apply[M[_]](implicit monad: Monad[M]): Monad[M] = monad
def flatMap[M[_],T,U](m: M[T])(fn: (T) => M[U])(implicit monad: Monad[M]) = monad.flatMap(m)(fn)
def map[M[_],T,U](m: M[T])(fn: (T) => U)(implicit monad: Monad[M]) =
+ def foldM[M[_],T,U](fn: (T,U)=>M[T])(acc: T)(xs: GenTraversable[U])(implicit monad: Monad[M]) =
johnynek Mar 8, 2013 Collaborator

can you move the order to be:

def foldM[M[_],T,U](acc: T, xs: GenTraversable[U])(fn: (T,U)=>M[T])(implicit monad: Monad[M])

So the ordering matches the way we normally write (and we can do):

foldM(0, List(1,2,3,4)) { (x,y) => if(x < 3) None else Some(x + y) }
ccsevers commented Mar 8, 2013

No objections to moving foldM and changing the order. Will do so and recommit.


Okay, moved into the Object, added a test for fun.

@johnynek johnynek merged commit 79b88e4 into twitter:develop Mar 12, 2013

1 check passed

default The Travis build passed
@ccsevers ccsevers deleted the ccsevers:add_foldM branch Mar 12, 2013
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment