Check if all numbers in a list are different in prolog

后端 未结 7 1397
失恋的感觉
失恋的感觉 2021-01-18 10:02

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 tru
7条回答
  •  情话喂你
    2021-01-18 10:53

    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).
    

提交回复
热议问题