Skip to content

Instantly share code, notes, and snippets.

Created January 8, 2013 14:47
Show Gist options
  • Save anonymous/4484300 to your computer and use it in GitHub Desktop.
Save anonymous/4484300 to your computer and use it in GitHub Desktop.
A simple instance of a trait which reflects side-effecting stateful changes that can be undone.
//Unlike a State Monad or some derived type, does not retain the previous state. Instead, just retains a means of "undoing" some stateful
//side effect. Still not sure if I completely like it as it doesn't indicate that it is intended to be used with an IO like action.
trait Change[+A]{
def map[B](f: A => B): Change[B]
def flatMap[B](f: A => B): Change[B]
}
case class Reversible[A+](value: A, undo: List[() => Unit]) extends Change[A]{
def map[B](f: A => B) = Reversible(f(value), undo)
def flatMap[B](f: A => Something[B]) = f(value) match{
case Reversible(x, u) => Reversible(x, u :: undo)
case Irreversible(x) => Reversible(x, undo)
}
}
case class Irreversible[A+](value: A) extends Change[A]{
def map[B](f: A => B) = Irreversible(f(value))
def flatMap[B](f: A => Something[B]) = f(value)
}
@wheaties
Copy link

wheaties commented Jan 8, 2013

Damn it, forgot to log in... AAaarrggg...

@wheaties
Copy link

wheaties commented Jan 8, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment