Created
March 31, 2016 07:33
-
-
Save mnd999/587838e0c7588cc4c10d5a6b6a9ad2c0 to your computer and use it in GitHub Desktop.
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
import scala.collection.immutable.List | |
object StackLanguage extends App { | |
var program = List(Value(1), Value(2), Value(3), Operator(_ + _), Operator(_ - _), UnaryOperator(Math.sqrt(_).toInt)) | |
println("Tim & Matt lovin the Scalay goodness") | |
def evaluate_stack(stack: List[Element]) = { | |
stack match { | |
case (head :Operator) :: tail => { | |
head.eval(tail) | |
} | |
case (head :UnaryOperator) :: tail => { | |
head.eval(tail) | |
} | |
case list => { | |
list | |
} | |
} | |
} | |
def evaluate_program(program: List[Element]): List[Element] = { | |
program.foldLeft(List[Element]())((stack, element) => { | |
evaluate_stack(element :: stack) | |
}) | |
} | |
sealed trait Element { | |
} | |
case class Operator(func: (Int, Int) => Int) extends Element { | |
def eval(stack : List[Element]) : List[Element] = stack match { | |
case (a: Value) :: (b : Value) :: tail => { | |
Value(func(a.n,b.n)) :: tail | |
} | |
} | |
} | |
case class UnaryOperator(func: Int => Int) extends Element { | |
def eval(stack : List[Element]) : List[Element] = stack match { | |
case (a: Value) :: tail => { | |
Value(func(a.n)) :: tail | |
} | |
} | |
} | |
case class Value(n: Int) extends Element { | |
} | |
print(evaluate_program(program)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment