尝试在 Scala 中为虚构的 Partial 类型实现 Kleisli 类别(阅读 Bartosz Milewski 的“程序员的类别理论”,这是第 4 章的练习题)
object Kleisli {
type Partial[A, B] = A => Option[B]
implicit class KleisliOps[A, B](f1: Partial[A, B]) {
def >=>[C](f2: Partial[B, C]): Partial[A, C] =
(x: A) =>
for {
y <- f1(x)
z <- f2(y)
} yield z
def identity(f: Partial[A, B]): Partial[A, B] = x => f(x)
}
val safeRecip: Partial[Double, Double] = {
case 0d => None
case x => Some(1d / x)
}
val safeRoot: Partial[Double, Double] = {
case x if x < 0 => None
case x => Some(Math.sqrt(x))
}
val safeRootRecip: Partial[Double, Double] = safeRoot.>=>(safeRecip)
safeRootRecip(1d)
safeRootRecip(10d)
safeRootRecip(0d)
}
IDE (IntelliJ) 没有显示错误,但是当我运行此代码段时,我得到:
Error:(27, 57) value >=> is not a member of $line5.$read.$iw.$iw.Kleisli.Partial[Double,Double]
val safeRootRecip: Partial[Double, Double] = safeRoot.>=>(safeRecip)
>=>
在隐式类之外定义工作正常。可能是什么原因?