Check if all numbers in a list are different in prolog

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

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

提交回复
热议问题