1
votes

I don't know Prolog at all, but still I need to understand what this program does. Compiler shows that there're 2 syntax errors, but the main logic of this program should still be understandable.

domains
 value=symbol
 level=integer
 ltype1=s(value,level)
 ltype2=tree(value,ltype2,ltype2); void
 list1=ltype1*

predicates
 append(list1,list1,list1)
 totree(ltype2,integer,list1)

clauses
 append([],X,X).
 append([X|T],Y,[X|Z]):-append(T,Y,Z).

 totree(void,_,[]).
 totree(tree(X,Y,Z),N,[s(X,N)|TA]):-
    K=N+1,
    totree(Y,K,TA1),
    totree(Z,K,TA2),
    append(TA1,TA2,TA).

goal
 totree(
    tree(a,tree(b,tree(c,void,void),tree(e,void,void)),tree(d,void,void)),
    1,C),
 write(C),
 totree(W,1,
          [s(a,1),s(b,2),s(c,3),s(e,3),s(d,2)]).
1
This is a bit unclear. You haven't said what the errors are. But it looks like you're trying to run a Turbo/PDC/Visual Prolog program in SWI which will not work. Turbo, PDC, and Visual Prolog are non-standard Prolog implementations. The sectioning into domains, predicates, clauses, and goal are unique to those implementations. You basically have to get rid of the domains and predicates section. clauses are the predicates that you are trying to define. goal should either be written as a predicate or called directly. There are other differences in implementations as well. - lurker

1 Answers

0
votes

This is the program you can run:

append([],X,X).
append([X|T],Y,[X|Z]):-
    append(T,Y,Z).

totree(void,_,[]).
totree(tree(X,Y,Z),N,[s(X,N)|TA]):- 
    K is N+1,
    totree(Y,K,TA1),
    totree(Z,K,TA2),
    append(TA1,TA2,TA).

If you run the query

?-totree(tree(a,tree(b,tree(c,void,void),tree(e,void,void)),tree(d,void,void)),1,C).

the result will be

C = [s(a, 1), s(b, 2), s(c, 3), s(e, 3), s(d, 2)].

The predicate totree/3 accepts as input:

  • a tree represented as tree(RootElement,Left,Right) where Left and Right are the left and right subtrees,
  • a number wich is the level of the tree where you are
  • and returns a list wich is the representation of the tree.

Let's analyze the result.

  • s(a,1): the element a is at the level 1 of the tree, correct because is the root (level 1 because is specified in the query).
  • s(b,2): the element b is at the level 2 of the tree, correct because b is the left child of a.
  • s(c,3): the element c is at the level 3 of the tree, correct because c is the left child of b and also a leaf.
  • and so on...

This is the definiton of append/3: append(List1,List2,List3) List3 is the concatenation of List1 and List2 (this predicate is already available in some libraries as lists.