Skip to content

Instantly share code, notes, and snippets.

@paradigmatic
Created August 17, 2011 18:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paradigmatic/1152232 to your computer and use it in GitHub Desktop.
Save paradigmatic/1152232 to your computer and use it in GitHub Desktop.
package org.example
import annotation.tailrec
import com.google.caliper.Param
class CaseOrder extends SimpleScalaBenchmark {
abstract class Expr
case class Var(name: String) extends Expr
case class Number(num: Double) extends Expr
case class UnOp(operator: String, arg: Expr) extends Expr
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr
object ExprFirst {
def simplify(expr: Expr): Expr = expr match {
// Some basic simplification rules...
case UnOp("-", UnOp("-", e)) => simplify(e) // Double negation
case BinOp("+", e, Number(0)) => simplify(e) // Adding zero
case BinOp("-", e, Number(0)) => simplify(e) // Subtracting zero
case BinOp("*", e, Number(1)) => simplify(e) // Multiplying by one
case BinOp("*", e, Number(0)) => Number(0) // Multiplying by zero
case _ => expr // Default, could not simplify given above rules
}
}
object ExprLast {
def simplify(expr: Expr): Expr = expr match {
// Some basic simplification rules...
case BinOp("+", e, Number(0)) => simplify(e) // Adding zero
case BinOp("-", e, Number(0)) => simplify(e) // Subtracting zero
case BinOp("*", e, Number(1)) => simplify(e) // Multiplying by one
case BinOp("*", e, Number(0)) => Number(0) // Multiplying by zero
case UnOp("-", UnOp("-", e)) => simplify(e) // Double negation
case _ => expr // Default, could not simplify given above rules
}
}
@tailrec
private def buildInput( start: Expr, n: Int ): Expr =
if( n == 0 ) start
else buildInput( UnOp("-", start ), n-1)
val input = buildInput( Var("x"), 100000 )
def timeForFirst( reps: Int ) = repeat(reps) {
ExprFirst.simplify( input )
}
def timeForLast( reps: Int ) = repeat(reps) {
ExprLast.simplify( input )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment