I want to create a rule in prolog that checks if there's a repeated number in a list.
For example:
[1,2,3,4]
it will return true
. [1,2,3,3]
it will return false
because the 3
is repeatedI came up with this rule but it doesn't work
Different([]).
Different([H|T]):-
Member(H,T),
Different(T).
Any ideas?
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.
Try this: same(X, X). same([A| B], [C| D]):- A=C, same(B,D). it'll return true if they are the same.
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.
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)).
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).
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