首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >K/ Kestrel Combinator for monads?

K/ Kestrel Combinator for monads?
EN

Stack Overflow用户
提问于 2015-10-13 18:22:07
回答 1查看 638关注 0票数 5
代码语言:javascript
运行
复制
implicit class KComb[A](a: A) {
  def K(f: A => Any): A = { f(a); a }
}

有了这个K组合子的实现,我们可以在应用副作用的同时将方法调用链接到一个值上,而不需要temp变量。例如:

代码语言:javascript
运行
复制
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。

代码语言:javascript
运行
复制
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附加到众所周知的方法(例如foldLeftMfoldMapMifMuntilMwhileM)的一元变体的模式。

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

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

发布于 2018-08-03 11:22:31

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

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

代码语言:javascript
运行
复制
getDocument flatTap print >>= process

getDocument >>! print >>= process

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33100183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档