Skip to content

Instantly share code, notes, and snippets.

@travisbrown
Created March 14, 2017 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save travisbrown/46a7801f3d2adc1a09bea25f15829519 to your computer and use it in GitHub Desktop.
Save travisbrown/46a7801f3d2adc1a09bea25f15829519 to your computer and use it in GitHub Desktop.
import cats.{ Applicative, Eval, Foldable, Monoid }, cats.implicits._
def foldMapM[F[_]: Foldable, G[_]: Applicative, A, B: Monoid](fa: F[A])(f: A => G[B]): G[B] =
fa.foldRight(Eval.always(Monoid[B].empty.pure[G]))((a, acc) => f(a).map2Eval(acc)(_ |+| _)).value
def sumIfSmall(s: Stream[Int]) = foldMapM(s) {
case n if n < 100 => Right(n)
case n => Left(n)
}
sumIfSmall(Stream.from(0)) // Left(100)
@mtk
Copy link

mtk commented Mar 15, 2017

newb question: Left and Right are from?

@aeons
Copy link

aeons commented Mar 15, 2017

scala.util

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment