如何将Throwable \ / List [Throwable \ / A]序列化为scalaz中的Throwable \ / List [A]?

时间:2014-02-05 19:49:21

标签: scala scalaz

我正在尝试弄清楚如何干净地将Throwable \/ List[Throwable \/ A]排序为Throwable \/ List[A],可能使用Traverse的{​​{1}}实例,但我可以'似乎弄清楚如何获得List right的应用。现在,这是我的非类型解决方案:

\/

我确信必须有更好的方法来实施import scalaz._ def readlines: Throwable \/ List[String] = ??? def parseLine[A]: Throwable \/ A = ??? def parseLines[A](line: String): Throwable \/ List[A] = { val lines = readlines lines.flatMap { xs => xs.reverse.foldLeft(right[Throwable, List[A]](Nil)) { (result, line) => result.flatMap(ys => parseA(line).map(a => a :: ys)) } } }

1 个答案:

答案 0 :(得分:2)

您可以使用sequenceUList[Throwable \/ String]转换为Throwable \/ List[String](它只保留第一个Throwable),而您应该像这样使用flatMap

def source: Throwable \/ List[Throwable \/ String] = ???
def result: Throwable \/ List[String] = source.flatMap{_.sequenceU}

您也可以使用traverseU代替map + sequenceU

def readlines: Throwable \/ List[String] = ???
def parseLine[A](s: String): Throwable \/ A = ???

def parseLines[A](): Throwable \/ List[A] =
  readlines flatMap { _ traverseU parseLine[A] }

使用for-comprehension:

def parseLines[A](): Throwable \/ List[A] =
  for {
    l <- readlines
    r <- l traverseU parseLine[A]
  } yield r