Reordering parentheses using associative property in Racket

别来无恙 提交于 2019-12-24 06:37:16

问题


I am having trouble implementing a function that given something like this:

'((+(d + e) + f) + (a + (a + c))

Returns this:

'(d + (e + (f + (a + (a + c)))))

Now the catch is that I have to use associativity to get the answer so I only want to use this property:

'((a + b) + c) = '(a + (b + c))

To get the correct output. I know how to implement the function for this case:

'((a + b) + c) -> '(a + (b + c))

However I cannot seem to figure out how to implement it for the first case above (or any other case larger than three items). I am not looking for answers only some guidance. If you would like to see code snippets let me know and I can post some. Also, I created a function that stripped the '+ from the list to make it easier to process.

I think this defines the grammar:

var ::=  a | b | c | d | e | f | g
fpip ::= var | (fpip + fpip)

Where a valid fpip can be:

fpip = '((a + b) + c)

or

fpip = '((a + b) + (c + d))

and at it's most atomic level:

fpip = '(a + b)

edit: yes the initial '+ should be erased. Regardless of how many plus signs there are in the initial input there should only be (amount-of-vars - 1) '+ in the output. For example:

'(+ + + + (a + b) + + c) -> '(a + (b + c)

回答1:


I think these are the cases to consider. Let's call the the recursive rewriter REWRITE.

var                               -> var
(var + var)                       -> (var + var)
(var + (fip1 + fpip2))            -> (var + (REWRITE (fip1 + fpip2))
((fip1 + fpip2) + var)            -> (REWRITE (fip1 + (fip2 + var))
((fip1 + fpip2) + (fip3 + fpip4)) -> (REWRITE (fip1 + (fip2 + (fip3 + fip4))))


来源:https://stackoverflow.com/questions/49864511/reordering-parentheses-using-associative-property-in-racket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!