Skip to content

Instantly share code, notes, and snippets.

@iainmcgin
Created July 20, 2011 01:21
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 iainmcgin/1094143 to your computer and use it in GitHub Desktop.
Save iainmcgin/1094143 to your computer and use it in GitHub Desktop.
Simple evaluator in Scala
abstract class Term[A]
case class Val[A](v : A) extends Term[A]
case class Fn[A, B](f : A => B) extends Term[A => B]
case class Apply[A, B](fn : Term[A => B], input : Term[A]) extends Term[B]
def eval[A](input : Term[A]) : A = input match {
case Val(v) => v
case Fn(f) => f
case Apply(m,d) => eval(m)(eval(d))
}
def badEval[A](input : Term[A]) : A = input match {
case Val(v) => v
case Fn(f) => f
// here is where we do not eval(v) first, which should be a type error!
case Apply(m,v) => eval(m)(v)
}
val five = Val(5)
val timesFive = Fn({x : Int => x * 5})
val fiveTimesFive = Apply(timesFive, five)
println("eval gives:" + eval(fiveTimesFive))
println("badEval gives:" + badEval(fiveTimesFive))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment