Created
June 6, 2016 21:20
-
-
Save dwhitney/9e3760064eacb573c86727906c073e58 to your computer and use it in GitHub Desktop.
Shows how the Freenion works
This file contains hidden or 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 freek._ | |
import cats.{Id,~>} | |
import cats.data.Xor | |
import cats.free.Free | |
object XorExample extends App{ | |
sealed trait Algebra[A] | |
case object Good extends Algebra[Xor[Throwable,String]] | |
case object Bad extends Algebra[Xor[Throwable,String]] | |
type PRG[A] = (Algebra :|: FXNil)#Cop[A] | |
def good: Free[PRG,Xor[Throwable,String]] = Good.freek[PRG] | |
def bad: Free[PRG,Xor[Throwable,String]] = Bad.freek[PRG] | |
val interpreter = new (Algebra ~> Id){ | |
def apply[A](fa: Algebra[A]): A = fa match { | |
case Good => Xor.Right("Good") | |
case Bad => Xor.Left(new RuntimeException("Bad")) | |
} | |
} | |
type O = Xor[Throwable,?] :&: Bulb | |
val freenionRight = for{ | |
str <- good.onionT[O] | |
} yield str | |
val onionMappedRight = freenionRight.map{ str => | |
str + " job sir!" | |
} | |
val freeRight = onionMappedRight.free | |
println(freeRight.foldMap(Interpreter(interpreter).nat)) //Right(Good job sir!) | |
val freenionLeft = for{ | |
str <- bad.onionT[O] | |
} yield str | |
val onionMappedLeft = freenionLeft.map{ str => | |
str + "this will never happen because of the Left" | |
} | |
val freeLeft = onionMappedLeft.free | |
println(freeLeft.foldMap(Interpreter(interpreter).nat)) //Left(java.lang.RuntimeException: Bad) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment