Skip to content

Instantly share code, notes, and snippets.

@dsugden
Last active August 29, 2015 13:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsugden/9774094 to your computer and use it in GitHub Desktop.
Save dsugden/9774094 to your computer and use it in GitHub Desktop.
StateT with Option and Either
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