scala - Scala - 是否有映射 Seq[A] => Seq[Either[Throwable, B]] 的函数?
问题描述
我正在寻找一个coll: Seq[A]
在应用函数f: A => B
并返回 a时映射集合的函数,Seq[Either[Throwable, B]]
以便可以在下游处理错误。
是否有类似的功能预烘焙到某个库中?也许是 Cats 或 Scalaz?
请参阅下面的我的实现:
import cats.syntax.either._
def eitherMap[A,B](f: A => B, coll: Seq[A]): Seq[Either[Throwable, B]] = {
coll.map { elem =>
Either.catchNonFatal(f(elem))
}
}
解决方案
每jwvh:coll.map(a => Try(f(a)).toEither)
似乎是完成此任务的最简单/最干净的方法。
推荐阅读
- c - 如何理解 xv6 引导代码中的以下代码?
- reactjs - React 服务器端渲染页面源未更新
- go - Goroutine 循环未完成
- reactjs - 将文件存储到 Laravel 的公共存储(ReactJS 和 Laravel)
- python - 如何在 Keras ConvLSTM 层中处理输入数据
- node.js - 在 Visual Studio 中构建 MS Word 插件时使用 NodeJS 服务器而不是本地 IIS 服务器
- apache-kafka - 消耗 -kafka 处理器不适用于 nifi UI?
- java - 递归划分三角形中的 NullPointerException
- mysql - 有没有办法判断 MySQL 联合查询中的结果集何时发生变化?
- ios - 将标签放在 UIView 的中间三分之一处