Last active
August 29, 2015 13:57
-
-
Save dsugden/9774094 to your computer and use it in GitHub Desktop.
StateT with Option and Either
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._ | |
import Scalaz._ | |
object StateTLearning extends App with StateTFunctions { | |
case class DB(v: Int) | |
val initial = DB(1) | |
type EitherString[+T] = \/[String, T] | |
type OptionStateT[T] = StateT[Option, DB, T] | |
type EitherStateT[T] = StateT[EitherString, DB, T] | |
val initialOptionState: OptionStateT[Unit] = constantStateT[Option, DB, Unit]({})(initial) | |
val initialEitherState: EitherStateT[Unit] = constantStateT[EitherString, DB, Unit]({})(initial) | |
def addWithOption(newV: Int): StateT[Option, DB, Int] = | |
if (newV < 0) | |
StateT[Option, DB, Int](s => None) | |
else | |
StateT[Option, DB, Int](s => Some { | |
val newvalue = s.v + newV | |
(s.copy(v = newvalue), newvalue) | |
}) | |
def addWithEither(newV: Int): StateT[EitherString, DB, Int] = | |
if (newV < 0) | |
StateT[EitherString, DB, Int](s => -\/("Number must be > 0")) | |
else | |
StateT[EitherString, DB, Int](s => \/- { | |
val newvalue = s.v + newV | |
(s.copy(v = newvalue), newvalue) | |
}) | |
val computeSomeStuffWithOption = initialOptionState.flatMap(x => addWithOption(2)).flatMap(x => addWithOption(3)) | |
println("OPTION 1 " +computeSomeStuffWithOption.run(initial)) | |
//OPTION 1 Some((DB(6),6)) | |
val computeSomeStuffWithOption2 = initialOptionState.flatMap(x => addWithOption(-1)) | |
println("OPTION 2" +computeSomeStuffWithOption2.run(initial).getOrElse("ERROR, None")) | |
//OPTION 2ERROR, None | |
val computeSomeStuffWithEither = initialEitherState.flatMap(x => addWithEither(2)).flatMap(x => addWithEither(3)) | |
println("EITHER 1 " +computeSomeStuffWithEither.run(initial)) | |
//EITHER 1 \/-((DB(6),6)) | |
val computeSomeStuffWithEither2 = initialEitherState.flatMap(x => addWithEither(-1)) | |
val runit = computeSomeStuffWithEither2.run(initial).fold(left => { | |
// got an error, try with another number | |
initialEitherState.flatMap(x => addWithEither(5)).run(initial) | |
},right => right ) | |
println("EITHER 2" +runit) | |
// EITHER 2\/-((DB(6),6)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment