【问题标题】:flatMap ignoring the resultflatMap 忽略结果
【发布时间】:2023-04-06 22:57:01
【问题描述】:

我想知道是否存在忽略flatMap 中的结果的函数(在 scala 或猫中)。例如

Some("ignore this").ignoreArgumentFlatMap(Some("result"))

相同
Some("ignore this").flatMap(_ => Some("result"))

【问题讨论】:

  • 用例会是什么?
  • 我有一些单子,结果实际上并不感兴趣,而只是内部状态
  • 例如for { x <- someFoo; _ <- anotherFoo: _ <- moreOtherFoo; _ <- derp } yield x - 以数据库事务为例
  • 不太确定这是否会对您有所帮助,但请查看github.com/oleg-py/better-monadic-for
  • 在你的情况下,不是Some("result").flatMap(x => { Some("ignore this"); Some(x) })(相当于你的理解)吗?

标签: scala monads scala-cats


【解决方案1】:

在猫中称为>>

scala> import cats.implicits._
import cats.implicits._

scala> Option("ignore this") >> Some("result")
res14: Option[String] = Some(result)

文档明确说明

fa.flatMap(_ => fb) 的别名。

与 *> 不同,fb 被定义为按名称参数,允许在计算 fb 不是堆栈安全的情况下使用此方法,除非在 flatMap 中暂停。

还有productR*>

scala> Option("ignore this").productR(Some("result"))
res15: Option[String] = Some(result)

scala> Option("ignore this") *> Some("result")
res16: Option[String] = Some(result)

就像文档所说的那样,它的论点不是按名称命名的。所以它或多或少相当于

val x0 = Some("result")
Some("ignore this").flatMap(_ => x0)

如果您想要另一种评估策略,可以使用 productREval

【讨论】:

  • “地图”是否也有类似物?例如x.ignoreMap(someValue) 会是 x.map(_ => someValue)?
  • @keksnicoh 我认为那是x.as(someValue),但它又不是别名。
猜你喜欢
  • 2021-05-27
  • 2015-03-22
  • 2016-07-01
  • 1970-01-01
  • 2021-05-16
  • 2015-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多