Prolog: permutations check and multiple answers
Posted
by Adrian
on Stack Overflow
See other posts from Stack Overflow
or by Adrian
Published on 2010-04-01T05:27:17Z
Indexed on
2010/04/01
5:33 UTC
Read the original article
Hit count: 744
Continuing to learn prolog, I'm trying to write a permutation(L1, L2) predicate. It should return true, only if L1 can be made up of all elements in L2. My code so far is the following:
permutation([], []).
permutation([H|T], L2) :- remove(L2, H, R), permutation(T, R).
Assuming that the predicate remove(L1, X, R) functions correctly, and it removes X from L1, I do not get correct results:
?- permutation([1],[1]).
true ;
false.
?- permutation([1, 2],[1]).
true ;
false.
?- permutation([1, 2],[1, 2]).
true ;
false.
?- permutation([1],[1, 2]).
false.
What am I missing.
Subquestion: What happens when the remove predicate returns two answers? My implementation returns the new, correct list, and then after pressing ; it returns the original list. Which answer does permutation predicate use?
?- remove([1,2,3], 3, R).
R = [1, 2] ;
R = [1, 2, 3].
© Stack Overflow or respective owner