【发布时间】:2015-10-13 10:22:06
【问题描述】:
implicit class KComb[A](a: A) {
def K(f: A => Any): A = { f(a); a }
}
鉴于 K 组合器的这种实现,我们可以在应用副作用的同时将方法调用链接到一个值上,而无需临时变量。 例如:
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 附加到众所周知方法的单子变体的模式(例如@987654329 @、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
【问题讨论】:
-
对于
IO,特别是有一个tap语法方法可以让你编写例如ma.flatMap(_.tap(IO.putStr)). -
@TravisBrown 啊,这很相似 - 不同之处在于
ma必须在被点击之前解包。我必须导入scalaz.syntax.effect.all._才能看到该方法。谢谢
标签: scala functional-programming monads higher-order-functions combinators