Cats - 当范围内的Monad`实例时如何使用for -reherehe?

Sam*_*uel 9 scala for-comprehension scala-cats

如何M在下面的方法中使用for-comprehension类型?

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

我会得到一个

value flatMap is not a member of type parameter M[Int]
Run Code Online (Sandbox Code Playgroud)

我可以通过定义flatMapmap方法来使它工作:

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)
}
Run Code Online (Sandbox Code Playgroud)

但是肯定有必要让Cats提供这些方法吗?

Alv*_*sco 19

尝试:

import cats.syntax.functor._, cats.syntax.flatMap._
Run Code Online (Sandbox Code Playgroud)