Skip to content

Instantly share code, notes, and snippets.

@mather
Created February 23, 2015 02:32
Show Gist options
  • Select an option

  • Save mather/1e05f14e168bed232910 to your computer and use it in GitHub Desktop.

Select an option

Save mather/1e05f14e168bed232910 to your computer and use it in GitHub Desktop.
Calculator Sample
// "sealed" : Declare that no other subclass except this file. This helps compiler to verify loss of pattern.
sealed trait Expression {
def a: Int
def b: Int
}
case class Addition(a: Int, b: Int) extends Expression
case class Subtraction(a: Int, b: Int) extends Expression
case class Multiply(a: Int, b: Int) extends Expression
case class Division(a: Int, b: Int) extends Expression
class Calculator {
/**
* Wrap result of unsafe operation into Option[T]
*/
def calc(exp: Expression): Option[Int] = exp match {
case Addition(a, b) => Some(a + b)
case Subtraction(a, b) => Some(a - b)
case Multiply(a, b) => Some(a * b)
case Division(a, 0) => None // Zero-division
case Division(a, b) => Some(a / b)
}
def showResult(exp: Expression) = {
calc(exp) match {
case Some(result) => s"${exp} => ${result}"
case None => "Failed to calculate"
}
}
}
/**
* Create singleton object of Calcurator.
* separete Calculator specification into class.
* This object implements how to manipurate Calcurator actually.
*/
object Calculator extends Calculator {
import scala.util.Random
val intLimit = 100
/**
* Return single expression at random
*/
def generateRandomExpression = {
val (a,b) = (Random.nextInt(intLimit), Random.nextInt(intLimit))
Random.nextInt(4) match {
case 0 => Addition(a, b)
case 1 => Subtraction(a, b)
case 2 => Multiply(a, b)
case _ => Division(a, b)
}
}
/**
* main
*/
def main(args: Array[String]): Unit = {
val expressions = List.fill(10) { generateRandomExpression }
expressions.map(showResult(_)).foreach(println)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment