Skip to content

Commit

Permalink
Merge e197d58 into e592e31
Browse files Browse the repository at this point in the history
  • Loading branch information
eed3si9n committed Jun 21, 2015
2 parents e592e31 + e197d58 commit d086843
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
11 changes: 11 additions & 0 deletions core/src/main/scala/cats/Foldable.scala
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,17 @@ import simulacrum._
def foldMap[A, B](fa: F[A])(f: A => B)(implicit B: Monoid[B]): B =
foldLeft(fa, B.empty)((b, a) => B.combine(b, f(a)))

/**
* Left associative monadic folding on `F`.
*/
def foldM[G[_], A, B](fa: F[A], z: B)(f: (B, A) => G[B])
(implicit G: Monad[G]): G[B] =
partialFold[A, B => G[B]](fa)({a: A =>
Fold.Continue({ b =>
(w: B) => G.flatMap(f(w, a))(b)
})
}).complete(Lazy { b: B => G.pure(b) })(z)

/**
* Traverse `F[A]` using `Applicative[G]`.
*
Expand Down
6 changes: 6 additions & 0 deletions tests/src/test/scala/cats/tests/FoldableTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ class FoldableTestsAdditional extends CatsSuite {
// more basic checks
val names = List("Aaron", "Betty", "Calvin", "Deirdra")
assert(F.foldMap(names)(_.length) == names.map(_.length).sum)
val sumM = F.foldM(names, "") { (acc, x) => (Some(acc + x): Option[String]) }
assert(sumM == Some("AaronBettyCalvinDeirdra"))
val notCalvin = F.foldM(names, "") { (acc, x) =>
if (x == "Calvin") (None: Option[String])
else (Some(acc + x): Option[String]) }
assert(notCalvin == None)

// test trampolining
val large = (1 to 10000).toList
Expand Down

0 comments on commit d086843

Please sign in to comment.