There is a wonderful problem set called Ninety-Nine Prolog Problems. Problem P70 is the one referred to in the title. And here is a great Prolog solution of this problem which takes only 5 lines. However, my understanding of Prolog is limited.
How does this solution look like in a C-like form (no itertools available)?
Edited by request. I hope I do not violate copyright.
The problem:
Syntax in BNF:
tree ::= letter forest '^'
forest ::= | tree forest
A nice solution using difference lists:
tree(TS,T) :- atom(TS), !, atom_chars(TS,TL), tree_d(TL-[ ],T). % (+,?)
tree(TS,T) :- nonvar(T), tree_d(TL-[ ],T), atom_chars(TS,TL). % (?,+)
tree_d([X|F1]-T, t(X,F)) :- forest_d(F1-['^'|T],F).
forest_d(F-F,[ ]).
forest_d(F1-F3,[T|F]) :- tree_d(F1-F2,T), forest_d(F2-F3,F).
Problem Definition
(taken from P-99: Ninety-Nine Prolog Problems)
We suppose that the nodes of a multiway tree contain single characters. In the depth-first order sequence of its nodes, a special character
^has been inserted whenever, during the tree traversal, the move is a backtrack to the previous level.By this rule, the tree in the figure is represented as:
afg^^c^bd^e^^^(source: ti.bfh.ch)
Define the syntax of the string and write a predicate
tree(String,Tree)to construct theTreewhen theStringis given. Work with atoms (instead of strings). Make your predicate work in both directions.Solution Part 1:
String2TreeThis is easy with a stack. Here’s the pseudocode:
The use of a dummy
rootnode simplifies matters. Essentially the algorithm is as follows:'^', we simply pop off the top of the stackSolution Part 2:
Tree2StringThe opposite direction is a matter of simple recursion:
As specified in the problem, we insert
^whenever we backtrack to the previous level.