Skip to content

Instantly share code, notes, and snippets.

@afsalthaj
Created August 17, 2018 01:25
Show Gist options
  • Save afsalthaj/6649ec23175c693b44390b407191c623 to your computer and use it in GitHub Desktop.
Save afsalthaj/6649ec23175c693b44390b407191c623 to your computer and use it in GitHub Desktop.
// This might look really simple, but people often get carried away validationNel (applicative) and disjunctions (monad) ended up having only errors (or a error) or a valid right.
// However we can go one step forward. Maximum error accumulation + Max computation (try hard, try hard)
import scalaz._, Scalaz._
def process1(int: Int): Int = throw new Exception("errors")
def process2(int: Int) : Int = int + 1
def process3(int: Int) : Int = int + 2
def process4(int: Int): Int = throw new Exception("errors2")
// The output should be NonEmptyList[errors, anotherError] \/ (intialValue + 1 + 2)
def `try`(f: Int => Int): State[(List[String], Int), Unit] = {
State.modify[(List[String], Int)](
s => \/.fromTryCatchNonFatal(f(s._2)) match {
case -\/(r) => (s._1 :+ r.getMessage, s._2)
case \/-(r) => (s._1, r)
}
)
}
def ss: State[(List[String], Int), Unit] =
for {
_ <- `try`(process1)
_ <- `try`(process2)
_ <- `try`(process3)
_ <- `try`(process4)
} yield ()
ss exec((Nil, 0))
// Result
// res24: (List[String], Int) = (List("errors", "errors2"), 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment