[英]Scala: Linux like pipe with error handling using Either
我对Scala比较陌生。
尝试开发一种模式以允许“级联”编程。 我们的目标是能够像Linux方式一样,在Linux的“管道”中从左到右链接数据操作,同时拖动其中一种方法可能返回的任何错误。 因此,在链的末尾有一个Either。
我无法将其归结为单个运算符-如果它返回简单的结果或已经包装在Either中的结果,则似乎必须根据运算符右边的方法进行区分。
在这里要求批评/提示/指向这样做的现有库的指针
谢谢
type PResult[R] = Either[String, R]
implicit class fromVal[A](val in: A) {
def |>[B](f: A => B): PResult[B] = Right(f(in))
def |>>[B](f: A => PResult[B]): PResult[B] = f(in)
}
implicit class fromEither[A](val in: PResult[A]) {
def |>[B](f: A => B): PResult[B] =
in match {
case Left(l) => Left(l)
case Right(r) => Right(f(r))
}
def |>>[B](f: A => PResult[B]): PResult[B] =
in match {
case Left(l) => Left(l)
case Right(r) => f(r)
}
}
val f1: Int => Int = _ + 2 //> f1 : Int => Int = <function1>
val f2: Int => PResult[Int] = { in => Right(in + 3) }
//> f2 : Int => piper.PResult[Int] = <function1>
22 |>> f2 |> f1 |>> f2 //> res0: piper.PResult[Int] = Right(30)
我认为类似的东西可以用于期货或其他可能导致成功或失败的事物。
我的确意识到我的|>和| >>与map和flatMap非常相似。
而且,如果我将我想做的事情与理解力进行比较(它们也不是同质的),那么对于选项或某些东西中包含的内容,您必须使用<- ,而=只是计算。 那么我想念了什么,有什么可以改善的呢?
我认为您可以像这样重写第二个隐式:
implicit class fromEither[A](val in: Either[String, A]) {
def |>[B](f: A => B) = in.right.map(f)
def |>>[B](f: A => Either[String, B]) = in.right.flatMap(f)
}
您还可以使其扩展AnyVal
,这应该会稍微提高性能。 我什至不会定义第一个隐式类。 不必将第一个元素包装在Right
cat somefile
麻烦,就像处理cat somefile
。
请注意,实际上有一个用于运行进程http://www.scala-lang.org/api/current/#scala.sys.process.package的unix管道式API。
如果您想将其带入更高的层次,可以查看迭代和枚举。 参见http://www.playframework.com/documentation/2.1.x/Enumeratees 。 它允许你做这样的事情strings |>> toInt &>> sum
,其中strings
列举一些字符串, toInt
到整数他们中的每一个转换和sum
并将它们相加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.