Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prolog - why does variable not get bound?

Tags:

list

prolog

I have defined a goal lowerpartition/3 as follows:

lowerpartition(X,P,Z) :- var(Z),!,lowerpartition(X,P,[]).
lowerpartition([],_,_).
lowerpartition([X|Xs],P,Z) :- X=<P, lowerpartition(Xs,P,[X|Z]).
lowerpartition([X|Xs],P,Z) :- X>P, lowerpartition(Xs,P,Z).

when I call

lowerpartition([1,2,3,4,5],3,X).

I expect X to be bound to the list [3,2,1], but Prolog just returns false. What am I doing incorrectly?

like image 457
Froskoy Avatar asked Sep 13 '26 00:09

Froskoy


1 Answers

It seems that you are mixing an accumulator-based approach with a stack based approach. Your first clause:

lowerpartition(X,P,Z) :- var(Z),!,lowerpartition(X,P,[]).

will leave Z uninstantiated, it is not used after checking that it is a variable therfore it won't be unified...

Try this:

lowerpartition([], _, []).
lowerpartition([X|Xs], P, [X|Zs]):-
  X =< P, lowerpartition(Xs, P, Zs).
lowerpartition([X|Xs], P, Zs):-
  X > P, lowerpartition(Xs, P, Zs).
like image 122
gusbro Avatar answered Sep 15 '26 13:09

gusbro