简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM