在monad上调用`getOrElse`的通用方法

时间:2018-10-24 08:52:43

标签: scala functional-programming scala-cats

我是scala-cats库的新手, 最初,我创建了一个通用代码,该代码根据我提供的monoid组合了monad:

\\ implicitly uses cats catsDataMonoidForEither
Monoid[Either].combine(Right("foo"), Left(new NullPointerException))
\\ returns: Left(NullPointerException)

\\ implicitly uses a monoid that I provided
Monoid[Option[String]].combine(Some("foo"), Some("bar"), None)
\\ returns: Some("foobar")

问题是我得到了不同的monad(我也希望能够处理ValidatedTry),并且我正在寻找一种通用方式来“ “ getOrElse”根据 monad 的任何FP抽象的预定义偏差,如下所示:

def getOrEmpty[M, A](monad: M[A])(implicit monadM: Monad[M], monoidA[A]): A = {
    // Method "magicallyGetOrElse" is supposed to get a monad,
    // if its is the biased side (Some, Right etc.) return the value,
    // else return the monad's A
    monadM.magicallyGetOrElse(monad)(monoidA.empty)

我该怎么做呢?

0 个答案:

没有答案