0

I have for example the following function computing the set of all internal nodes in a binary tree (nodes which have at least one child, i.e. are no leaves)

internals(nil,[]).
internals(t(_,nil,nil),[]).
internals(t(X,L,nil),[X|S]) :- L = t(_,_,_), internals(L,S).
internals(t(X,nil,R),[X|S]) :- R = t(_,_,_), internals(R,S).
internals(t(X,L,R),[X|S]) :- L = t(_,_,_), R = t(_,_,_), 
   internals(L,SL), internals(R,SR), append(SL,SR,S).

the result of this is

?- internals(t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil))), X).
X = [3, 2, 5] ;
false.

Why does it end in false and how come the following code does the same but does not result in false

internals(nil,[]).
internals(t(_,nil,nil),[]) :- !.
internals(t(X,L,R),[X|Xs]):-
    internals(L,LI), internals(R,RI),
    append(LI,RI,Xs).

?- internals(t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil))), X).
X = [3, 2, 5].
false
  • 10,264
  • 13
  • 101
  • 209
Wouter Vandenputte
  • 1,948
  • 4
  • 26
  • 50
  • 2
    In the first example, after the first solution was found, Prolog determined there are other logical paths to explore (there was a *choice point*) so it prompted you with the first solution. When you entered `;` you asked Prolog to seek more solutions. It found no more solutions, so it outputs `false`. That's standard behavior. In your second example, there was no choice point after finding the first solution, so the choice wasn't presented. – lurker Aug 18 '18 at 13:16
  • Your cut-version succeeds incorrectly for `internals(t(1,nil,nil),[1]).` – false Aug 19 '18 at 00:42

0 Answers0