K / Kestrel Combinator for monads?

时间:2015-10-13 10:22:07

标签: scala functional-programming monads higher-order-functions combinators

implicit class KComb[A](a: A) {
  def K(f: A => Any): A = { f(a); a }
}

考虑到K组合子的这种实现,我们可以在应用副作用的同时对值进行链接方法调用,而不需要临时变量。 E.g:

case class Document()
case class Result()

def getDocument: Document = ???
def print(d: Document): Unit = ???
def process(d: Document): Result = ???

val result = process(getDocument.K(print))
// Or, using the thrush combinator
// val result = getDocument |> (_.K(print)) |> process

现在,我需要做类似的事情,但改为使用IO monad。

def getDocument: IO[Document] = ???
def print(d: Document): IO[Unit] = ???
def process(d: Document): IO[Result] = ???

我的问题是:这个操作的组合器是否已存在? Scalaz或者其他库中有什么可以做到的吗?

我找不到任何东西,所以我自己为monad推出了K组合子的变体。 我称之为tapM,因为1)K组合在Ruby中被称为tap而在Scalaz中被称为unsafeTap 2)看起来Scalaz遵循将M附加到monadic变体的模式众所周知的方法(例如foldLeftMfoldMapMifMuntilMwhileM)。

但我仍然想知道这种类型是否存在,我只是重新发明轮子。

implicit class KMonad[M[_]: Monad, A](ma: M[A]) {

  def tapM[B](f: A => M[B]): M[A] =
    for {
      a <- ma
      _ <- f(a)
    } yield a
}

// usage
getDocument tapM print flatMap process

1 个答案:

答案 0 :(得分:1)

编辑:我的最初答案被误导了。这是正确的。

在猫的flatTap上有一种FlatMap方法,在scalaz的>>!上有一种BindOps

getDocument flatTap print >>= process

getDocument >>! print >>= process

编辑^ 2:将flatMap更改为>>=,以便更轻松地显示点击和绑定之间的关系。

相关问题