Created
September 24, 2012 22:39
-
-
Save Mahoney/3778890 to your computer and use it in GitHub Desktop.
Boolean Logic in Pure Scala - 3rd cut
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
sealed abstract class Boolean { | |
... | |
def ifTrue[T](doWhenTrue: => T): Option[T] | |
... | |
} | |
case object true1 extends Boolean { | |
... | |
override def ifTrue[T](doWhenTrue: => T): Option[T] = Some(doWhenTrue) | |
... | |
} | |
case object false1 extends Boolean { | |
... | |
override def ifTrue[T](doWhenTrue: => T): Option[T] = None | |
... | |
} | |
object Conditional { | |
def if1[T](boolean: Boolean)(doWhenTrue: => T): IfResult[T] = { | |
val resultOfIfTrue = boolean.ifTrue(doWhenTrue) | |
return new IfResult(boolean, resultOfIfTrue) | |
} | |
class IfResult[T] private[Conditional] (boolean: Boolean, resultOfIfTrue: Option[T]) { | |
def elseif(boolean: Boolean)(doWhenTrue: => T): IfResult[T] = { | |
val ifResultIfAlreadyTrue = resultOfIfTrue.map(_=> this) | |
return ifResultIfAlreadyTrue.getOrElse(new IfResult(boolean, boolean.ifTrue(doWhenTrue))) | |
} | |
def else1(doWhenFalse: => T): T = { | |
return resultOfIfTrue.getOrElse(doWhenFalse) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment