scala - 组成 scalaz io 效果对象
问题描述
我正在尝试将 scalaz 的 ioeffect IO[E,A] monad 用于一段非常有效的代码。
我试图用 IO[E,A] 在高级别重写的代码需要一些关于存储在云中的文件的元数据。该代码试图:
- 下载文件
- 从文件中提取字符串
- 构建一个包含文件文本内容的 pojo
- 将 pojo 提交给一些队列/restful 服务
步骤的细节并不那么重要,但我想做的是按照以下方式做一些事情:
def processShareActivity(fileObject: FileObject): IO[ProcessFileFailure, IndexResponse] = {
for {
file <- downloadFile (fileObject)
text <- extractText (file)
searchFileObject <- IO.point(buildSearchFileObject (fileObject, file, text))
indexedResponse <- indexSearchFileObject (searchFileObject)
} yield indexedResponse
}
def indexSearchFileObject(fileObject: SearchFileObject): IO[IndexFailure, IndexResponse] = ???
def buildSearchFileObject(fileObject: FileObject, file: File, str: String): SearchFileObject = ???
def extractText(file: File): IO[ExtractionFailure, String] = ???
def downloadFile(fileObject: FileObject): IO[DownloadFileFailure, File] = ???
问题是,一个实例似乎IO[E,A]
并IO[F,B]
没有组合。也就是说,由于 exampledownloadFile
的 IO 签名DownloadFileFailure
为其错误场景返回并extractText
返回ExtractionFailure
,因此这些 monad 似乎无法构成for
理解。
是否有一种简单的方法可以让我的顶级for
理解进行组合,从而导致在子方法中可能发生的不同类型的故障IO[ProcessFileFailure, IndexResponse]
周围ProcessFileFailure
存在某种包装故障对象?
解决方案
不幸的是,您确实需要一种方法将这些错误统一为一个常见错误:
例如:
sealed trait ProcessFileFailure
object ProcessFileFailure {
case class Index(e: IndexFailure) extends ProcessFileFailure
case class Extraction(e: ExtractionFailure) extends ProcessFileFailure
case class Download(e: DownloadFileFailure) extends ProcessFileFailure
}
你的理解将变成:
for {
file <- downloadFile (fileObject).leftMap(ProcessFileFailure.Download)
text <- extractText (file).leftMap(ProcessFileFailure.Extraction)
searchFileObject <- IO.point(buildSearchFileObject (fileObject, file, text))
indexedResponse <- indexSearchFileObject (searchFileObject).leftMap(ProcessFileFailure.Index)
} yield indexedResponse
它很尴尬,但它确实具有能够存储所有错误以及发生错误的上下文的优势。
推荐阅读
- scala - 为什么 Mockito verifyNoMoreInteractions 对 Scala 默认值有问题
- java - 在java中使用回溯的迷宫问题中的老鼠
- java - 部署问题,即使在 pom 中也找不到类
- python - 使用无头 chrome 设置代理时面临的问题
- javascript - 一次只允许打开一个菜单 - React
- java - System.out 临时重定向后的奇怪控制台输出
- r - 通过 R 中的官员在 powerpoint 中的语句之前添加项目符号
- c# - c#从一个文件夹中的多个csv文件中检索详细信息
- android - 通过通知侦听器服务从通知中提取图像
- c++ - 我重载了一个虚函数,但它不起作用