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 } } 
7
  • Why not simply println(12 + 3 + 5)? ;) Commented Mar 6, 2016 at 12:13
  • I'm trying to build a calculator for the user enters a string and the program calculates the result Commented Mar 6, 2016 at 12:16
  • @csharpfolk that doesn't work as the parse function returns String Commented Mar 6, 2016 at 12:19
  • @ps0604 that was just the idea, you need to change parse signature to return Int of course Commented Mar 6, 2016 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 Commented Mar 6, 2016 at 12:29

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

what if I need to add division and multiplication?
then you have to use a real parser.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.