Skip to content

Instantly share code, notes, and snippets.

@nomisRev
Last active July 9, 2017 19:02
Show Gist options
  • Save nomisRev/88961508c21a786047d0de7abbb0d3f0 to your computer and use it in GitHub Desktop.
Save nomisRev/88961508c21a786047d0de7abbb0d3f0 to your computer and use it in GitHub Desktop.
sealed class MathExpression {
fun eval(): Result = when (this) {
is Addition -> left.eval().flatMap { ll -> right.eval().map { rr -> ll + rr } }
is Subtraction -> left.eval().flatMap { ll -> right.eval().map { rr -> ll - rr } }
is Division -> right.eval().flatMap { rr -> if (rr == 0) Failure("Division by zero") else left.eval().map { ll -> ll/rr }}
is Number -> Success(value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment