Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 430
Samuel Avatar asked Nov 16 '17 23:11

Samuel


1 Answers

Try:

import cats.syntax.functor._, cats.syntax.flatMap._
like image 137
Alvaro Carrasco Avatar answered Oct 08 '22 21:10

Alvaro Carrasco