Check if all numbers in a list are different in prolog

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

    The rule provided in the question is very close to a correct answer with minimal library usage. Here's a working version that required only one change, the addition of \+ in the third row:

    uniqueList([]).
    uniqueList([H|T]):-
         \+(member(H,T)),
         uniqueList(T).
    

    Explanation of the code for Prolog beginners: The member(H,L) predicate checks if element H is a member of the list L. \+ is Prolog's negation function, so the above code amounts to:

    uniqueList([H|T]) returns true if: (H doesn't have a copy in T) and uniqueList(T)
    

    Whereas the code by the original asker didn't work because it amounted to:

    uniqueList([H|T]) returns true if: (H has a copy in T) and uniqueList(T)
    

    *I renamed Different() to uniqueList() because it reads better. Convention is to reserve capital letters for variables.

提交回复
热议问题