Check if all numbers in a list are different in prolog

后端 未结 7 1398
失恋的感觉
失恋的感觉 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:54

    A neat way I came up with is the following:

    If all members of a list are different from each other, then if I tell prolog to choose all pairs (I,J) such that I,J are members of the list and also I is equal to J, then for each element in the list it will only be able to find one such pair, which is the element with itself.

    Therefore, if we can put all such pairs in a list, then the length of this list should be of the same length of the original list.

    Here's my prolog code:

    all_diff(L) :-
            findall((I,J), (member(I, L), member(J, L), I == J), List),
            length(L, SupposedLength),
            length(List, CheckThis),
            SupposedLength == CheckThis.
    

提交回复
热议问题