I’d like to get some help in the following exam problem, I have no idea how to do this:
Input: a list of numbers, eg.: [1,2,3,4]
Output: every possible correct bracketing. Eg.: (in case of input [1,2,3,4]):
((1 2) (3 4))
((1 (2 3)) 4)
(1 ((2 3) 4))
(1 (2 (3 4)))
(((1 2) 3) 4)
Bracketing here is like a method with two arguments, for example multiplication – then the output is the possible multiplication orders.
Your assignment could be seen as the inverse of ‘computing the yield of a binary tree’.
You can code
yieldwith 2 recursive calls and append/3:test:
Thus abstractly,
yield/2should solve your assignment, when called in this way:but, of course, that do not terminate. Clearly, the SLD resolution (Prolog computing algorithm) can’t solve this problem without some help.
But if you recall that append/3 can generate all the alternatives left & right lists that compose the appended:
you can attempt to change the order of calls to get your solution.
Beware that you need sufficiently instantiated arguments before recursing, thus check the ‘output’ of append. You can test with
I also suggest to rename the predicate and change the order of arguments for clarity: