Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all numbers in a list are different in prolog

Tags:

prolog

I want to create a rule in prolog that checks if there's a repeated number in a list.

For example:

  • for [1,2,3,4] it will return true.
  • for [1,2,3,3] it will return false because the 3 is repeated

I came up with this rule but it doesn't work

Different([]).
Different([H|T]):-
     Member(H,T),
     Different(T).

Any ideas?

like image 687
user1730250 Avatar asked Nov 21 '13 21:11

user1730250


People also ask

How do you check if a list contains a value in Prolog?

If you want to check if a list contains a member, use memberchk/2 . so memberchk(I/J, Item) succeeds if I/J is in the list Item . Your include/3 predicate has no base case, and attempt to ensure that every element of the given list is I/J , so it will always fail.

How do you check if two lists have the same Prolog?

Try this: same(X, X). same([A| B], [C| D]):- A=C, same(B,D). it'll return true if they are the same.

What is Maplist in Prolog?

maplist(Goal, List) is true if and only if Goal can be successfully applied to List. If Goal fails for any of List's elements, maplist fails.


2 Answers

a compact definition could be

all_diff(L) :- \+ (select(X,L,R), memberchk(X,R)).

i.e. all elements are different if we can't peek one and find it in the rest...

edit

Let's (marginally) improve efficiency: it's useless to check if X is member of the prefix sublist, so:

all_diff(L) :- \+ (append(_,[X|R],L), memberchk(X,R)).
like image 195
CapelliC Avatar answered Sep 21 '22 23:09

CapelliC


The simplest way to check that all list members are unique is to sort list and check that length of the sorted list is equal of length of the original list.

different(X) :-
    sort(X, Sorted),
    length(X, OriginalLength),
    length(Sorted, SortedLength),
    OriginalLength == SortedLength.

Your solution doesn't work because of wrong syntax (facts and predicates should not begin with a capital letter) and a logic error. List is unique if head H is not a member of a tail T of a list and tail T is unique:

different([]).
different([H|T]):-
    \+member(H,T),
    different(T).
like image 23
ДМИТРИЙ МАЛИКОВ Avatar answered Sep 20 '22 23:09

ДМИТРИЙ МАЛИКОВ