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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With