[英]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.