Created
October 18, 2017 14:29
-
-
Save phenan/63833c2cc715c96c02a4c33e17d9e2ac to your computer and use it in GitHub Desktop.
scala.util.Try[T] と同様に使える Throwable \/ T の型エイリアス
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scalaz._ | |
/** | |
* Tries[T] is a type alias of Throwable \/ T. | |
* It can be used in the same manner as scala.util.Try but it is an instance of monad unlike Try. | |
* | |
* Created by phenan on 2017/10/18. | |
*/ | |
package object tries { | |
type Tries[+T] = Throwable \/ T | |
object Tries { | |
def apply [T] (v: => T): Tries[T] = try \/-(v) catch { case e: Throwable => -\/(e) } | |
} | |
object Succeeds { | |
def apply [T] (v: => T): Tries[T] = \/-(v) | |
} | |
object Fails { | |
def apply (e: => Throwable): Tries[Nothing] = -\/(e) | |
} | |
implicit class TriesUtil [T] (t: Tries[T]) { | |
def filters (f: T => Boolean): Tries[T] = t match { | |
case \/-(v) if f(v) => \/-(v) | |
case \/-(v) => -\/(new NoSuchElementException("Predicate does not hold for " + v)) | |
case -\/(e) => -\/(e) | |
} | |
def catches (f: PartialFunction[Throwable, T]): T = t match { | |
case \/-(v) => v | |
case -\/(e) if f.isDefinedAt(e) => f(e) | |
case -\/(e) => throw e | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
/ の filter は Throwable が Monoid でないため使えないので、代わりに filters メソッドを用意。
catches は try-catch みたいに使えるように用意してみた。