3

Given a method

def f[A, B, C](a: A) : Kleisli[Future, B, C] = ???

I need a combinator working with an Option[A]

My first try was :

def g[A, B, C](a: Option[A], default: => C) = a match {
  case Some(a) => save(a)
  case None => Kleisli[Future, B, C] { _ => Future.successful(default) }
}

But after reading How to combine sequence of Kleisli, I came up with a better version :

def g[A, B, C](a: Option[A], default: => C) : Kleisli[Future, B, C] = 
  a.traverseU(f[A, B, C]).map(_.getOrElse(default))

Any idea to improve ?

Community
  • 1
  • 1
Yann Moisan
  • 8,161
  • 8
  • 47
  • 91
  • That looks fine to me. You could also use `fold` on the `a` directly and lift `default` into a `Kleisli` for the empty side, but that's not likely to end up any nicer. – Travis Brown Apr 08 '16 at 17:25

1 Answers1

0

Here is the implementation of the idea suggested in comment by @TravisBrown.

def g[A, B, C](a: Option[A], default: => C) : Kleisli[Future, B, C] =
  a.fold(Future(default).liftKleisli[B])(f)

Readability is maybe better.

Yann Moisan
  • 8,161
  • 8
  • 47
  • 91