I'm trying to figure out how to sequence a Throwable \/ List[Throwable \/ A] into a Throwable \/ List[A] in a cleanly, possibly using the Traverse instance for List, but I can't seem to figure out how to get the applicative for the right of \/. Right now, here is the non-typeclass solution I have:
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))
}
}
}
I'm sure there has to be a better way to implement parseLines.
You could use sequenceU to transform List[Throwable \/ String] to Throwable \/ List[String] (it will preserve only first Throwable) and than you should just use flatMap like this:
def source: Throwable \/ List[Throwable \/ String] = ???
def result: Throwable \/ List[String] = source.flatMap{_.sequenceU}
You could also use traverseU instead of 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] }
Using for-comprehension:
def parseLines[A](): Throwable \/ List[A] =
for {
l <- readlines
r <- l traverseU parseLine[A]
} yield r
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With