Why OptionT doesn't work for Try?

I'm looking at this question from Scala and Scalaz views. OptionT

works for Future

but not Try

. What is the reason for the absence OptionT

for Try

, where there is a usecase function, i.e. def foo(i: Int): Try[Option[Int]] = ...

may or may not return a value, and sometimes a network exception happens? Thanks to

+3


source to share


1 answer


Cause Try is not a valid functor .

You will need to use skazus-out-auls or write your own Try instances. Here's a working example with scalaz-outlaws' Try instances :



import scala.util.{Try,Success,Failure}
import scalaz._
import Scalaz._

implicit val tryOutlawInstances = new Traverse[Try] with Monad[Try] with Plus[Try]{
  def point[A](a: ⇒ A): Try[A] = Success(a)
  override def map[A,B](fa: Try[A])(f: A ⇒ B) = fa map f
  def bind[A,B](fa: Try[A])(f: A ⇒ Try[B]) = fa flatMap f
  def traverseImpl[F[_], A, B](fa: Try[A])(f: A ⇒ F[B])(implicit F: Applicative[F]) : F[Try[B]] = fa match {
    case Success(a) ⇒ F.map(f(a))(Success.apply)
    case Failure(f) ⇒ F.point(Failure(f))
  }
  def plus[A](a: Try[A], b: ⇒ Try[A]) = a orElse b
}

val foo = Try("foo".some)
val result = OptionT(foo).map(x => x.toUpperCase).run

      

+3


source







All Articles