How to use Scalaz's traverse and traverseU with Either

╄→尐↘猪︶ㄣ 提交于 2019-12-24 05:32:10

问题


Is it possible to use Scalaz' traverse and traverseU with Either instead of Option?

For the following code:

val list = List(1, 2, 3)

def f(i: Int): Either[Int, String] =
  if (i > 2) Left(i)
  else Right("must be lower than 3")

I want to traverse list with f and either return the first Right(msg) if there is one or more failure, or Left(list) if everything went right.


回答1:


Is there any reason why you're not using Validation and NonEmptyList by scalaz?

You can easily do something like

def f(i: Int) =
  if (i > 2) i.successNel
  else "something wrong".failureNel

List(1, 2, 3).traverseU(f) // Failure(NonEmptyList(something wrong, something wrong))
List(3, 4, 5).traverseU(f) // Success(List(3, 4, 5))

If you instead want to fail on the first error, you can use \/, aka the scalaz version of Either which is isomorphic to scala.Either but right-biased

def f(i: Int) =
  if (i > 2) \/-(i)
  else -\/("something wrong")

List(1, 2, 3).traverseU(f) // Failure(something wrong)
List(3, 4, 5).traverseU(f) // Success(List(3, 4, 5))


来源:https://stackoverflow.com/questions/27510386/how-to-use-scalazs-traverse-and-traverseu-with-either

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!