Created
July 20, 2011 01:21
-
-
Save iainmcgin/1094143 to your computer and use it in GitHub Desktop.
Simple evaluator in Scala
This file contains hidden or 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
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