I’m writing a function called subseq which checks if one list is a subsequence of another.
subseq([],[]).
subseq([],[Y|Ys]).
subseq([X|Xs],[Y|Ys]) :- X=:=Y, subseq(Xs,Ys).
subseq([X|Xs],[Y|Ys]) :- X=\=Y, subseq([X|Xs],Ys).
When I try subseq(X,[1,2]) I get:
X = [] ? ;
uncaught exception: error(instantiation_error,(=:=)/2)
Why is this happening? My guess is that [] is being operated on by =:=, but how do I check for/prevent this error?
You use
=:=and=\=in the wrong context here. Those two operators should be used when you have two expressions at hand and want to evaluate and compare them. In your test, becauseXis not known beforehand, Prolog couldn’t evaluateXand compare withY. More information about=:=and=\=could be found here: Prolog Operator =:=.In your code you only need unification for atoms so one possible fix could be: