Scala 单子的K/红隼组合器?

Scala 单子的K/红隼组合器?,scala,functional-programming,monads,higher-order-functions,combinators,Scala,Functional Programming,Monads,Higher Order Functions,Combinators,考虑到K组合器的这个实现,我们可以在应用副作用的同时对一个值进行链式方法调用,而不需要临时变量。 例如: 现在,我需要做一些类似的事情,但是使用IO单子 case class Document() case class Result() def getDocument: Document = ??? def print(d: Document): Unit = ??? def process(d: Document): Result = ??? val result = process(ge

考虑到K组合器的这个实现,我们可以在应用副作用的同时对一个值进行链式方法调用,而不需要临时变量。 例如:

现在,我需要做一些类似的事情,但是使用IO单子

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
我的问题是:这个操作的组合器是否已经存在?Scalaz或者其他图书馆里有没有这样的东西

我什么也找不到,所以我自己为单子推出了这个
K
组合器的变体。 我称之为
tapM
,因为1)K组合子在Ruby中称为
tap
,在Scalaz中称为
unsafeTap
,2)Scalaz似乎遵循了将
M
附加到已知方法的一元变体的模式(例如,
foldLeftM
foldMapM
ifM
untilM
whileM

但我还是想知道是否已经存在类似的东西,我只是在重新发明轮子

def getDocument: IO[Document] = ???
def print(d: Document): IO[Unit] = ???
def process(d: Document): IO[Result] = ???
隐式类KMonad[M[\ux]:Monad,A](ma:M[A]){
def tapM[B](f:A=>M[B]):M[A]=
为了{

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

在猫的
FlatMap
上有
flatTap
方法,在scalaz的
BindOps上有
方法

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

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

对于
IO
特别是有一个
tap
语法方法,允许您编写例如
ma.flatMap(u.tap(IO.putStr))
@TravisBrown啊,这很相似-不同的是,
ma
在被点击之前必须被打开。我必须导入
scalaz.syntax.effect.all.\u
来查看该方法。谢谢
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
getDocument flatTap print >>= process

getDocument >>! print >>= process