Guest User

Untitled

a guest
Oct 19th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. import scalaz._
  2.  
  3. /**
  4. * Tries[T] is a type alias of Throwable \/ T.
  5. * It can be used in the same manner as scala.util.Try but it is an instance of monad unlike Try.
  6. *
  7. * Created by phenan on 2017/10/18.
  8. */
  9. package object tries {
  10. type Tries[+T] = Throwable \/ T
  11.  
  12. object Tries {
  13. def apply [T] (v: => T): Tries[T] = try \/-(v) catch { case e: Throwable => -\/(e) }
  14. }
  15.  
  16. object Succeeds {
  17. def apply [T] (v: => T): Tries[T] = \/-(v)
  18. }
  19.  
  20. object Fails {
  21. def apply (e: => Throwable): Tries[Nothing] = -\/(e)
  22. }
  23.  
  24. implicit class TriesUtil [T] (t: Tries[T]) {
  25. def filters (f: T => Boolean): Tries[T] = t match {
  26. case \/-(v) if f(v) => \/-(v)
  27. case \/-(v) => -\/(new NoSuchElementException("Predicate does not hold for " + v))
  28. case -\/(e) => -\/(e)
  29. }
  30.  
  31. def catches (f: PartialFunction[Throwable, T]): T = t match {
  32. case \/-(v) => v
  33. case -\/(e) if f.isDefinedAt(e) => f(e)
  34. case -\/(e) => throw e
  35. }
  36. }
  37. }
Add Comment
Please, Sign In to add comment