简体   繁体   中英

The optimal way of performing different side effects depending on whether the Validation is Success or Failure

I expect the solution not to be based on the obvious pattern matching of if-else. I'm sure there should be more natural ways to do it, like combination of map and getOrElse on Option.

Validation有一种fold方法,可以选择产生副作用:

v.fold(e => println("Ouch, we got "+e), a => println("Yay!!  We got "+a))
Validation.fold

用字符填写答案......

For completeness, you may wish to operate on the Validation after side-effecting with it:

object Test {
  import scalaz._
  import syntax.bifunctor._
  import syntax.validation._
  def f(s: String) = { println(s"Err ${s}"); s }
  def g(i: Int) = { println(s"Int ${i}"); i }
  def m(x: Validation[String, Int]) = x bimap (f, g)
  def n(x: Validation[String, Int]) = f _ <-: x :-> g _
  def main(args: Array[String]) {
    val v = 17.success[String]
    val w = "nope".failure[Int]
    println(m(v) map (i => i + 1))
    println(m(v)); println(m(w))
    println(n(v)); println(n(w))
  }
}

Or, you maybe just like operators with faces. Do emoticonic operators have a name in the functional community? Given my present mood, I'd try emoperator, as in mope, but that may be too narrow. Or "lolop"? But a usage like x :-> f is clearly a "facial expression."

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