Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add instance of MonadRec[Try] #1147

Merged
merged 1 commit into from
Jun 20, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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