How to transform a Kleisli[Try, I, A] into I => A

157 views Asked by At

Is there an existing combinator or a better way to write ?

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

There are 1 answers

0
bischak On

It is possible to do mapping on monadic value using Identity:

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

Example:

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