检查列表中的所有数字是否在序言中都不同 [英] Check if all numbers in a list are different in prolog

查看:44
本文介绍了检查列表中的所有数字是否在序言中都不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 prolog 中创建一个规则来检查列表中是否有重复的数字.

I want to create a rule in prolog that checks if there's a repeated number in a list.

例如:

  • 对于 [1,2,3,4] 它将返回 true.
  • 对于 [1,2,3,3] 它将返回 false 因为 3 重复
  • for [1,2,3,4] it will return true.
  • for [1,2,3,3] it will return false because the 3 is repeated

我想出了这个规则,但它不起作用

I came up with this rule but it doesn't work

Different([]).
Different([H|T]):-
     Member(H,T),
     Different(T).

有什么想法吗?

推荐答案

一个紧凑的定义可能是

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

编辑

让我们(稍微)提高效率:检查 X 是否是前缀子列表的成员是没有用的,所以:

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

这篇关于检查列表中的所有数字是否在序言中都不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆