假设我在 processOne
中有一个 monadic 函数,定义如下:
def processOne(输入:输入):Either[ErrorType, Output] = ...
给定“Inputs
”列表,我想返回包含在 Either
中的相应“Outputs
”列表:
def processMany(输入:Seq[Input]):Either[ErrorType,Seq[Output]] = ...
processMany
将为其拥有的每个输入调用 processOne
,但是,我希望它在 processOne
第一次(如果有的话)时终止> 返回一个 Left
,并返回那个 Left
,否则返回一个带有输出列表的 Right
。
我的问题:实现processMany
的最佳方式是什么?是否可以使用 for
表达式来完成此行为,或者我是否有必要自己递归地迭代列表?
最佳答案
与 Scalaz 7:
def processMany(inputs: Seq[Input]): Either[ErrorType, Seq[Output]] =
inputs.toStream traverseU processOne
将 inputs
转换为 Stream[Input]
利用了 Stream
的非严格 traverse
实现,即给你你想要的短路行为。
顺便说一句,您标记了这个“monad”,但遍历只需要一个应用仿函数(碰巧,它可能是根据 Either
的 monad 定义的)。如需进一步引用,请参阅论文 The Essence of the Iterator Pattern ,或者,对于基于 Scala 的解释,Eric Torreborre 的 blog post关于这个问题。
关于scala - 将许多 Either 映射到一个 Either 与许多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15118199/