I am trying to compare the lists. Given function(List1,List2) and List1 has length N and List 2 has length M and N>M.
I want to check if any permutation of List2 happens to be the first M characters of List1.
eg,
predicate([a,c,b,d,e],[a,b,c,d]).
should be true and
predicate([a,c,b,e,d],[a,b,c,d]).
should be false.
Thank you.
Using the
permutation/2andprefix/2predicates you could write something such as :As a side note and to quote swi-prolog manual :
So I’d take care not to call
has_prefix_perm/2with a too lengthy second list, especially if it happens not to be a prefix modulo permutation, since all the cases will be tested.Another way would be to test if List1 items are members of List2 until List2 is empty, that way you know that a permutation exists :
Written like that, I wouldn’t use it on non ground lists, but seeing your OP I didn’t search further…
Another way would be to check if List1 reduced to the length of List2 is a permutation of List2 :
Another way would be to… I guess there are lots of ways to do that, just pick one that isn’t horrible complexity wise and fits your style ! 🙂
I’d go with the last one personally.