How to arrange Throwable \ / List [Throwable \ / A] in Throwable \ / List [A] in scalaz?

I am trying to figure out how to properly order Throwable \/ List[Throwable \/ A]in Throwable \/ List[A], possibly using an instance Traversefor List, but I cannot figure out how to get the application for rightof \/. Right now, this is a different solution from the class:

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 am sure there must be a better way to implement parseLines.

+3
source share
1 answer

You can use sequenceUto convert List[Throwable \/ String]to Throwable \/ List[String](it will save only the first Throwable), and you should just use it flatMaplike this:

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

You can also use traverseUinstead 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] }

:

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

All Articles