1
我想提起Either
中的部分函数。如何提升部分函数
有没有更好的办法:
def lift[A, B, C](pf : PartialFunction[A, B])(c: A => C) : A => Either[C, B] = { a => if (pf.isDefinedAt(a)) Right(pf(a)) else Left(c(a)) }
我想提起Either
中的部分函数。如何提升部分函数
有没有更好的办法:
def lift[A, B, C](pf : PartialFunction[A, B])(c: A => C) : A => Either[C, B] = { a => if (pf.isDefinedAt(a)) Right(pf(a)) else Left(c(a)) }
有很多写这个的其他方式,让你避免不愉快的isDefinedAt
:
def lift[A, B, C](pf: PartialFunction[A, B])(c: A => C): A => Either[C, B] =
(pf andThen Right.apply) orElse (PartialFunction(c andThen Left.apply))
或者:
def lift[A, B, C](pf: PartialFunction[A, B])(c: A => C): A => Either[C, B] =
(a: A) => pf.lift(a).fold[Either[C, B]](Left(c(a)))(Right(_))
例如。
Scalaz使得最后执行上面的toRight
更好一点:
import scalaz._, Scalaz._
def lift[A, B, C](pf: PartialFunction[A, B])(c: A => C): A => Either[C, B] =
(a: A) => pf.lift(a).toRight(c(a))
我可能会与某些版本的orElse
执行去,虽然。