我正在尝试弄清楚如何干净地将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))
}
}
}
。
答案 0 :(得分:2)
您可以使用sequenceU
将List[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