简体   繁体   中英

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?

尝试:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM