Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
def ifn(str: String): Int = expr(str.split(" ").toList)._1
// expr := term ["+"|"-" term]*
def expr(src: List[String]): (Int, List[String]) = {
//println(s"[expr] src: $src")
val (v1, src2) = term(src)
def expr2(v1: Int, src: List[String]): (Int, List[String]) = src match {
case "+"::src3 => {
val (v2, src4) = term(src3)
expr2(v1 + v2, src4)
}
case "-"::src3 => {
val (v2, src4) = term(src3)
expr2(v1 - v2, src4)
}
case _ => (v1, src)
}
expr2(v1, src2)
}
// term := factor ["*"|"/" factor]*
def term(src: List[String]): (Int, List[String]) = {
//println(s"[term] src: $src")
val (v1, src2) = factor(src)
def term2(v1: Int, src: List[String]): (Int, List[String]) = src match {
case "*"::src3 => {
val (v2, src4) = factor(src3)
term2(v1 * v2, src4)
}
case "/"::src3 => {
val (v2, src4) = factor(src3)
term2(v1 / v2, src4)
}
case _ => (v1, src)
}
term2(v1, src2)
}
// factor := Int
def factor(src: List[String]): (Int, List[String]) = {
(src.head.toInt, src.tail)
}
def test(src: String) = println(src + " = " + ifn(src))
test("1")
test("1 + 2")
test("1 + 2 + 3 + 4")
test("1 * 2 * 3")
test("1 + 2 * 3")
test("1 * 2 + 3")
test("2 * 3 * 4")
test("2 + 3 * 4")
test("2 * 3 + 4")
test("5 - 2")
test("1 - 2 - 3")
test("2 * 3 - 4 * 5 * 6 - 7 * 8")
test("100 / 10 / 5")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment