【问题标题】:K / Kestrel Combinator for monads?K / Kestrel Combinator for monads?
【发布时间】: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 @、foldMapMifMuntilMwhileM)。

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

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


【解决方案1】:

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

在猫的FlatMap 上有一个flatTap 方法,在scalaz 的BindOps 上有一个&gt;&gt;!

getDocument flatTap print >>= process

getDocument >>! print >>= process

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-02
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多