Created
January 8, 2013 14:47
-
-
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.
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
//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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Damn it, forgot to log in... AAaarrggg...