简体   繁体   English

如何将Throwable \\ / List [Throwable \\ / A]序列化为scalaz中的Throwable \\ / List [A]?

[英]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 \\/ . 我试图弄清楚如何将Throwable \\/ List[Throwable \\/ A]序列化为Throwable \\/ List[A]干净利落,可能使用ListTraverse实例,但我似乎无法想象如何获得适用于\\/right 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 . 我确信必须有更好的方法来实现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: 你可以使用sequenceUList[Throwable \\/ String]Throwable \\/ List[String] (它只保留第一个Throwable ),你应该像这样使用flatMap

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

You could also use traverseU instead of map + 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] }

Using for-comprehension: 使用理解:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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