Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add more MonoidK based folds #4432

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions core/src/main/scala/cats/Traverse.scala
Original file line number Diff line number Diff line change
Expand Up @@ -187,9 +187,9 @@ trait Traverse[F[_]] extends Functor[F] with Foldable[F] with UnorderedTraverse[
mapWithLongIndex(fa)((a, long) => (a, long))

/**
* If `fa` contains the element at index `idx`,
* return the copy of `fa` where the element at `idx` is replaced with `b`.
* If there is no element with such an index, return `None`.
* If `fa` contains the element at index `idx`,
* return the copy of `fa` where the element at `idx` is replaced with `b`.
* If there is no element with such an index, return `None`.
*
* The behavior is consistent with the Scala collection library's
* `updated` for collections such as `List`.
Expand All @@ -213,6 +213,22 @@ trait Traverse[F[_]] extends Functor[F] with Foldable[F] with UnorderedTraverse[

override def unorderedSequence[G[_]: CommutativeApplicative, A](fga: F[G[A]]): G[F[A]] =
sequence(fga)

def foldTraverse[A, B, G[_]](fa: F[A])(f: A => G[B])(implicit G: Monad[G], M: Monoid[B]): G[B] =
foldM(fa, M.empty) { case (acc, a) =>
G.map(f(a)) { b =>
M.combine(acc, b)
}
}
BalmungSan marked this conversation as resolved.
Show resolved Hide resolved

def foldTraverseK[A, B, G[_], H[_]](fa: F[A])(f: A => G[H[B]])(implicit G: Monad[G], M: MonoidK[H]): G[H[B]] =
foldTraverse(fa)(f)(G, M.algebra)

def foldSequence[A, G[_]](fga: F[G[A]])(implicit G: Monad[G], M: Monoid[A]): G[A] =
BalmungSan marked this conversation as resolved.
Show resolved Hide resolved
foldTraverse(fga)(identity)

def foldSequenceK[A, G[_], H[_]](fgha: F[G[H[A]]])(implicit G: Monad[G], M: MonoidK[H]): G[H[A]] =
foldTraverseK(fgha)(identity)
}

object Traverse {
Expand Down