[comp.lang.prolog] m-way trees

bimbart@kulcs.uucp (Bart Demoen) (02/14/90)

> I have the following facts asserted in the prolog database:
> 
> 	linked(a, b).
> 	linked(a, c).
> 	linked(b, d).
> 	linked(b, e).
> 	linked(b, f).
> 
> and I want to construct an "m-way" tree strcuture as follows:
> 
> 		a
> 		|
> 	     -------
> 	     |     |
> 	     b     c
> 	     |
>          -----	   
> 	   | | |
> 	   d e f

make_tree/2 below does what you want: call it with first argument the top of the tree


make_tree(X,tree(X,LX)) :- bagof(TZ,Z^(linked(X,Z),make_tree(Z,TZ)),LX) , ! .
make_tree(X,tree(X,[])) .

the query:

	?- make_tree(a,T) .

answers

	T = tree(a,[tree(b,[tree(d,[]),tree(e,[]),tree(f,[])]),tree(c,[])])

this is perhaps not the fastest solution, neither does it work if your linked/2
database does not represent a tree ... but it is nice that it is so easy to
write such a tree constructor in Prolog

bimbart@kulcs.uucp