0

In this Scala code I'm trying to analyze a string that contains a sum (such as 12+3+5) and return the result (20). I'm using regex to extract the first digit and parse the trail to be added recursively. My issue is that since the regex returns a String, I cannot add up the numbers. Any ideas?

object TestRecursive extends App {

  val plus = """(\w*)\+(\w*)""".r

  println(parse("12+3+5"))

  def parse(str: String) : String = str match {

    // sum   
    case plus(head, trail) => parse(head) + parse(trail)

    case _ => str
  }


}
smilyface
  • 5,021
  • 8
  • 41
  • 57
ps0604
  • 1,227
  • 23
  • 133
  • 330
  • Why not simply `println(12 + 3 + 5)`? ;) – Maroun Mar 06 '16 at 12:13
  • I'm trying to build a calculator for the user enters a string and the program calculates the result – ps0604 Mar 06 '16 at 12:16
  • @csharpfolk that doesn't work as the parse function returns String – ps0604 Mar 06 '16 at 12:19
  • @ps0604 that was just the *idea*, you need to change `parse` signature to return Int of course – csharpfolk Mar 06 '16 at 12:27
  • @csharpfolk that's the point of the question, how to make the function return String and Int, depending on what is returned – ps0604 Mar 06 '16 at 12:29
  • whats the purpose of `parse` - to evaluate the expression, what will be value of the expression - a number. so let `parse` always return number like here `parse(s: String): Int` - everything should compile after that change - thats magic of recursion – csharpfolk Mar 06 '16 at 12:31
  • Try look at [this](http://stackoverflow.com/questions/11923378/evaluate-string-command-in-scala-from-repl), might save you the hard work? – Avihoo Mamka Mar 06 '16 at 12:40

1 Answers1

2

You might want to use the parser combinators for an application like this.

"""(\w*)\+(\w*)""".r also matches "+" or "23+" or "4 +5" // but captures it only in the first group.

what you could do might be

scala> val numbers = "[+-]?\\d+"
numbers: String = [+-]?\d+
                                   ^

scala> numbers.r.findAllIn("1+2-3+42").map(_.toInt).reduce(_ + _)
res4: Int = 42

scala> numbers.r.findAllIn("12+3+5").map(_.toInt).reduce(_ + _)
res5: Int = 20
Andreas Neumann
  • 10,734
  • 1
  • 32
  • 52