Skip to content

Commit

Permalink
Merge pull request #1147 from johnynek/oscar/tryMonadRec
Browse files Browse the repository at this point in the history
Add instance of MonadRec[Try]
  • Loading branch information
kailuowang authored Jun 20, 2016
2 parents c518d99 + df0bc85 commit caf9901
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
12 changes: 10 additions & 2 deletions core/src/main/scala/cats/std/try.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import TryInstances.castFailure

import scala.util.control.NonFatal
import scala.util.{Failure, Success, Try}
import scala.annotation.tailrec

trait TryInstances extends TryInstances1 {

// scalastyle:off method.length
implicit def catsStdInstancesForTry: MonadError[Try, Throwable] with CoflatMap[Try] with Traverse[Try] =
new TryCoflatMap with MonadError[Try, Throwable] with Traverse[Try] {
implicit def catsStdInstancesForTry: MonadError[Try, Throwable] with CoflatMap[Try] with Traverse[Try] with MonadRec[Try] =
new TryCoflatMap with MonadError[Try, Throwable] with Traverse[Try] with MonadRec[Try] {
def pure[A](x: A): Try[A] = Success(x)

override def pureEval[A](x: Eval[A]): Try[A] = x match {
Expand Down Expand Up @@ -57,6 +58,13 @@ trait TryInstances extends TryInstances1 {
case f: Failure[_] => G.pure(castFailure[B](f))
}

@tailrec final def tailRecM[B, C](b: B)(f: B => Try[(B Xor C)]): Try[C] =
f(b) match {
case f: Failure[_] => castFailure[C](f)
case Success(Xor.Left(b1)) => tailRecM(b1)(f)
case Success(Xor.Right(c)) => Success(c)
}

def handleErrorWith[A](ta: Try[A])(f: Throwable => Try[A]): Try[A] =
ta.recoverWith { case t => f(t) }

Expand Down
3 changes: 3 additions & 0 deletions tests/src/test/scala/cats/tests/TryTests.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ class TryTests extends CatsSuite {
checkAll("Try[Int] with Option", TraverseTests[Try].traverse[Int, Int, Int, Int, Option, Option])
checkAll("Traverse[Try]", SerializableTests.serializable(Traverse[Try]))

checkAll("Try", MonadRecTests[Try].monadRec[Int, Int, Int])
checkAll("MonadRec[Try]", SerializableTests.serializable(MonadRec[Try]))

test("show") {
forAll { fs: Try[String] =>
fs.show should === (fs.toString)
Expand Down

0 comments on commit caf9901

Please sign in to comment.