11

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?

Valy Dia
  • 2,781
  • 2
  • 12
  • 32
Samuel
  • 16,923
  • 6
  • 62
  • 75

1 Answers1

22

Try:

import cats.syntax.functor._, cats.syntax.flatMap._
Alvaro Carrasco
  • 6,103
  • 16
  • 24
  • 1
    Thanks. I was importing `cats.implicits._`, but I must have messed something up before when it was failing. It's working now. Thanks! – Samuel Nov 17 '17 at 01:15