I am attempting to create a Scala method that will take one parent group of parentheses, represented as a String, and then map each subgroup of parentheses to a different letter. It should then put these in a map which it returns, so basically I call the following method like this:
val s = "((2((x+3)+6)))"
val map = mapParentheses(s)
Where s could contain any number of sets of parentheses, and the Map returned should contain:
"(x+3)" -> 'a'
"(a+6)" -> 'b'
"(2b)" -> 'c'
"(c)" -> 'd'
So that elsewhere in my program I can recall ‘d’ and get “(c)” which will become “((2b))” then ((2(a+6))) and finally ((2((x+3)+6))). The string sent to the method mapParentheses will never have unmatched parentheses, or extra chars outside of the main parent parentheses, so the following items will never be sent:
- “(fsf)a” because the
ais outside the parent parentheses - “(a(aa))(a)” because the
(a)is outside the parent parentheses - “((a)” because the parentheses are unmatched
- “)a(“ because the parentheses are unmatched
So I was wondering if anyone knew of an easy (or not easy) way of creating this mapParentheses method.
Classic recursive parsing problem. It can be handy to hold the different bits. We’ll add a few utility methods to help us out later.
Now you need to parse into these things:
Now we’ve got the whole thing parsed. So let’s find all the bits.
Now we can build the map you want.
Evidence that it works:
I will leave it as an exercise to the reader to figure out how it works, with the hint that recursion is a really powerful way to parse recursive structures.