分离上的模式匹配

时间:2015-06-25 15:04:44

标签: scala scalaz

鉴于以下内容:

scala> val err: \/[String, Boolean \/ Int] = -\/("bad")
err: scalaz.\/[String,scalaz.\/[Boolean,Int]] = -\/(bad)

我写了一个函数,它接受\/[String, Boolean \/ Int]并返回Boolean \/ Int

scala> def f(x: \/[String, Boolean \/ Int]): \/[Boolean, Int] = x match {
     |       case -\/(_) => -\/(false)
     |       case \/-(y) => y
     | }
f: (x: scalaz.\/[String,scalaz.\/[Boolean,Int]])scalaz.\/[Boolean,Int]

它似乎按预期工作:

scala> f(err)
res6: scalaz.\/[Boolean,Int] = -\/(false)

scala> f(\/-(\/-(5))
     | )
res7: scalaz.\/[Boolean,Int] = \/-(5)

有没有更简洁,惯用的scalaz方法来做到这一点?

1 个答案:

答案 0 :(得分:3)

def f(x: \/[String, Boolean \/ Int]) = x.getOrElse(-\/(false))