【发布时间】:2017-12-06 20:41:52
【问题描述】:
我正在尝试弄清楚如何使用 scalaz7 IO 和 monad 转换器以优雅的纯函数式风格编写这段代码,但我无法理解它。
想象一下我有这个简单的 API:
def findUuid(request: Request): Option[String] = ???
def findProfile(uuid: String): Future[Option[Profile]] = redisClient.get[Profile](uuid)
使用这个 API,我可以像这样使用 OptionT 转换器轻松编写不纯函数:
val profileT = for {
uuid <- OptionT(Future.successful(findUuid(request)))
profile <- OptionT(findProfile(uuid))
} yield profile
val profile: Future[Option[Profile]] = profileT.run
正如您所注意到的 - 此函数包含具有副作用的 findProfile()。我想在 IO monad 内部隔离这种效果并在纯函数之外进行解释,但不知道如何将它们组合在一起。
def findProfileIO(uuid: String): IO[Future[Option[Profile]]] = IO(findProfile(uuid))
val profileT = for {
uuid <- OptionT(Future.successful(findUuid(request)))
profile <- OptionT(findProfileIO(uuid)) //??? how to put Option inside of the IO[Future[Option]]
} yield profile
val profile = profileT.run //how to run transformer and interpret IO with the unsafePerformIO()???
关于如何完成的任何建议?
【问题讨论】:
标签: scala scalaz monad-transformers io-monad