如何将Kleisli [Try,I,A]转换为I =>一个

时间:2017-09-11 21:14:44

标签: scala-cats kleisli

是否有现有的组合器或更好的写入方式?

def combine[I, A](k: Kleisli[Try, I, A], default: A) : I => A =
  k.run.andThen(_.getOrElse(default))

1 个答案:

答案 0 :(得分:0)

可以使用Identity:

对monadic值进行映射
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