使用 scalaz,您可以折叠 Option
b fold ( sb => A(sb) map (bb => C(i, some(bb))), C(i, none).success)
可能有一种简化sb => A(sb) map (bb => C(i, some(bb)))
使用无点样式的方法,但这在 scala 中通常很难看:
设置
scala> :paste
// Entering paste mode (ctrl-D to finish)
object A {
def apply(b: B): ValidationNEL[String, A] = sys.error("")
}
case class A()
case class B()
case class C(i: Int, a: Option[A])
// Exiting paste mode, now interpreting.
defined module A
defined class A
defined class B
defined class C
第一个实现
scala> def apply(i: Int, b: Option[B]): ValidationNEL[String, C] =
| b fold ( sb => A(sb) map (bb => C(i, some(bb))), C(i, none).success)
apply: (i: Int, b: Option[B])scalaz.Scalaz.ValidationNEL[String,C]
第二个实现
如果你声明一等函数,你就有更好的组合机会。例如:
object A { val fromB: B => ValidationNEL[String, A] = _ => sys.error("") }
object C { val fromA: Int => A => C = i => a => C(i, some(a)) }
defined module A
defined module C
然后
scala> def apply(i: Int, b: Option[B]): ValidationNEL[String, C] =
| b fold (A.fromB andThen (_ map C.fromA(i)), C(i, none).success)
apply: (i: Int, b: Option[B])scalaz.Scalaz.ValidationNEL[String,C]