Last active
August 29, 2015 13:58
-
-
Save ElectricCoffee/10006848 to your computer and use it in GitHub Desktop.
a simple program that evaluates a string and returns a result
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
package com.wausoft.main | |
import scala.collection.mutable.Stack | |
trait ImplicitClasses { | |
implicit class RichStack[A](stack: Stack[A]) { | |
def operate(op: (A, A) => A): Unit = { | |
val (b, a) = (stack.pop, stack.pop) | |
stack push op(a,b) | |
} | |
} | |
} |
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
package com.wausoft.main | |
import scala.collection.mutable.Stack | |
object Parser extends ImplicitClasses{ | |
def eval(str: String): Double = { | |
val s = str.toLowerCase split ' ' | |
val stack = new Stack[Double] | |
s.foreach(d => parse(d, stack)) | |
return if(stack.size > 0) stack.pop else 0 | |
} | |
def parse(input: String, stack: Stack[Double]): Unit = input match { | |
case "+" => stack.operate(_+_) | |
case "-" => stack.operate(_-_) | |
case "*" => stack.operate(_*_) | |
case "/" => stack.operate(_/_) | |
case "sqrt" => | |
val r = Math.sqrt(stack.pop) | |
stack push r | |
case n => stack push n.toDouble | |
} | |
} |
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
package com.wausoft.main | |
object Program { | |
// testing it out | |
def main(args: Array[String]): Unit = { | |
val r = Parser eval "5 1 2 + 4 * + 3 -" | |
// 5 | |
// 5 1 | |
// 5 1 2 | |
// 5 1 2 + => 5 3 | |
// 5 3 4 | |
// 5 3 4 * => 5 12 | |
// 5 12 + => 17 | |
// 17 3 | |
// 17 3 - => 14 | |
println(r) // prints 14.0 | |
println(Parser eval "2 sqrt") // prints 1.4142135623730951 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment