【问题标题】:Future with State monadState monad 的未来
【发布时间】:2014-09-11 02:27:58
【问题描述】:

我想使用 State monad 为第三方 API 提供的数据实现缓存。让我们想象一下 getThirdPartyData(key: String) 方法,它首先检查缓存,然后如果它不存在,则应该向 API 发出请求。我想到的第一个也是最天真的实现是在 Future 中包含 State 类型 -

Future[State[Cache, ThirdPartyData]]

但这是不正确的,因为当请求失败时,您将丢失缓存(getThirdPartyData 将返回 Failure)。

我想到的第二个选项是扩展,或者说重新定义 State monad - s => Future[(s,a)],而不是 s => (s,a),但我认为这是一个非常流行的问题,所以 scalaz 可能有一些已经定义的解决方法这个问题。

非常感谢任何帮助!

【问题讨论】:

  • S => Future[(S, A)] 是您使用 StateT[Future, S, A] 获得的结果,但它不会有您想要的行为 - 查找失败会使计算崩溃。

标签: scala functional-programming monads scalaz


【解决方案1】:

这是你要找的StateT[Future, Cache, ThirdPartyData]吗?

implicit val m: Monoid[ThirdPartyData] = ...
val startState: Cache = ...
val l: List[StateT[Future, Cache, ThirdPartyData]] = ...

val result = l.sequenceU
 .map { _.foldMap (identity)) }
 .eval (startState)

【讨论】:

    猜你喜欢
    • 2012-10-08
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 2014-02-18
    • 2013-05-16
    • 1970-01-01
    • 2011-05-07
    相关资源
    最近更新 更多