implicit class KComb[A](a: A) {
def K(f: A => Any): A = { f(a); a }
}
有了这个K组合子的实现,我们可以在应用副作用的同时将方法调用链接到一个值上,而不需要temp变量。例如:
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中,或者其他库中,有没有这样做的东西?
我找不到任何东西,所以我自己推出了K
组合器的这个变体。我之所以叫它tapM
,是因为1) K组合子在Ruby中称为tap
,在Scalaz中称为unsafeTap
;2) Scalaz似乎遵循了将M
附加到众所周知的方法(例如foldLeftM
、foldMapM
、ifM
、untilM
、whileM
)的一元变体的模式。
但我仍然想知道是否已经存在这样的东西,我只是在重新发明轮子。
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
发布于 2018-08-03 11:22:31
编辑:我最初的回答被误导了。这就是正确的答案。
在猫的FlatMap
上有一个flatTap
方法,在scalaz的BindOps
上有一个>>!
方法。
getDocument flatTap print >>= process
getDocument >>! print >>= process
编辑^2:将flatMap
更改为>>=
,以便更轻松地显示点击和绑定之间的关系。
https://stackoverflow.com/questions/33100183
复制相似问题