Samuel
Samuel

Reputation: 17171

Cats - how to use for-comprehension when `Monad` instance in scope?

How can I use for-comprehension on type M in the method below?

def foo[M[_]: Monad](m1: M[Int], m2: M[Int]) =
  for {
     a <- m1
     b <- m2
  } yield (a + b)

I'll get a

value flatMap is not a member of type parameter M[Int]

I can make it work by defining the flatMap and map methods like so:

implicit class MOps[A](m: M[A])(implicit monad: Monad[M]) {
  def flatMap[B](f: A => M[B]): M[B] = monad.flatMap(m)(f)
  def map[B](f: A => B): M[B]        = monad.map(m)(f)
}

But surely there must be a way for Cats to provide these methods?

Upvotes: 11

Views: 3215

Answers (1)

Alvaro Carrasco
Alvaro Carrasco

Reputation: 6172

Try:

import cats.syntax.functor._, cats.syntax.flatMap._

Upvotes: 22

Related Questions