【问题标题】:Scalaz: Bypass IO pipeline?Scalaz:绕过 IO 管道?
【发布时间】:2019-05-22 19:55:59
【问题描述】:

我不知道该怎么做,我想做的是:

 output1 <- step1(...)
 output2 <- step2(....)
 ....

我想要做的是针对特定的output1,我不想执行step2,而是通过它。 scalaz.zio.IO 有内置函数部分吗?

除了嵌套的flatMap,我找不到任何东西:

 step1(...).flatMap {
      case ... => step2(....)
      case ... => step3(...)
 }

但是当step2 也产生一个条件时,这会变得很丑,等等......

我也可以使用IO 的Left 部分,但我已经将它用于Exception 和错误跟踪。

IO[Error, IO[ByPassCondition, ResultForStep2]] 会起作用吗?但是如果设置了ByPassCondition,我将无法将ResultForStep2 传递给step2...

【问题讨论】:

  • 我对 Scalaz 的 IO 不熟悉,但是 if-guard 有用吗?类似于output2 &lt;- step2(...) if cond(output1)。
  • 可以,但是当我有多个条件或需要绕过多个条件时,它会变得混乱。

标签: scala functional-programming scalaz


【解决方案1】:

我找到了解决办法:

implicit class JumpIO[A, B](io: IO[A, (B, Boolean)]) {
  def mightJumpNext(next: B => IO[A, B]): IO[A, B] = {
    io.flatMap { case (b, test) =>
      if (test) {
        io.map { case (bb, _) => bb }
      } else {
        io.flatMap { case (bb, _) => next(bb) }
      }
    }
  }

  def mightJumpNextChain(next: B => IO[A, (B, Boolean)]): IO[A, (B, Boolean)] = {
    io.flatMap { case (_, test) =>
      if (test) {
        io.map { case (bb, _) => (bb, false) }
      } else {
        io.flatMap { case (bb, _) => next(bb) }
      }
    }
  }
}

那么你可以这样做:

  io
    .mightJumpNext(b=> step2(b))
    .mightJumpNext(b => step3(b))
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多