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

StackOverflow https://stackoverflow.com/questions/21587053

  •  07-10-2022
  •  | 
  •  

質問

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top