是否有现有的组合器或更好的编写方式?
def combine[I, A](k: Kleisli[Try, I, A], default: A) : I => A =
k.run.andThen(_.getOrElse(default))
是否有现有的组合器或更好的编写方式?
def combine[I, A](k: Kleisli[Try, I, A], default: A) : I => A =
k.run.andThen(_.getOrElse(default))
可以使用 Identity 对一元值进行映射:
def combine[I, A](k: Kleisli[Try, I, A], default: A): I => A =
k.mapF[Id, A](_.getOrElse(default)).run
例子:
scala> val div = Kleisli[Try, Int, String](x => Try(1000 / x).map(_.toString))
div: cats.data.Kleisli[scala.util.Try,Int,String] = Kleisli(<function1>)
scala> combine(div, "Good")(10)
res0: String = 100
scala> combine(div, "Division by zero")(0)
res1: String = Division by zero