I have a String like val s = "5 - 3 + 2" (there can be any number of additions/substractions). Using pattern matching I would like to calculate this expression (so for this example result would be 4). My first idea is to do something like this:
object calculator{
val s = "5 - 3 + 2"
val Pattern = "(\\d+)".r
def main(args: Array[String]) {
val matches = Pattern.findAllIn(s).toArray
for (mymatch <- matches) mymatch.toInt
var sum = 0
matches.foreach(sum += _)
println(sum)
}
}
It doesn't even assume that I can have substractions (I don't know how to do this), but there is an error: type mismatch; found : String#3416175 required: Int#1078
Another approach is to have a matcher and somehow evaluate these expressions there:
val Pattern = ((?:\\d+\\s*[-+]\\s+)*\\d+).r
def matcher(expression: String): Any = expression match {
case Pattern(expression) => expression //evaluate expression here?
case _ => "wrong expression"
}
Any ideas how to achieve this?