在列表中查找唯一项 [英] Finding Unique Items in a List

查看:49
本文介绍了在列表中查找唯一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个规则来决定项 X 是否恰好出现在列表 L 中.

I'm trying to write a rule which decides whether an item X occurs exactly one in a list L.

unique(X, [X|T]):- !, \+ member(X, T).
unique(X, [_|T]):- unique(X, T).

该规则用于确定一个值在列表中是否唯一,但是当我尝试使用 unique(X, [1,2,3,1,3,2,5,4,3,8]). 它只返回 false. 我期望的是这个(比如 member(X, list).:

The rule works for determining whether a value is unique within a list or nor, but when I try to get unique values within a list using unique(X, [1,2,3,1,3,2,5,4,3,8]). it returns just false. What I expected is this (like member(X, list).:

X = 5 ;
X = 4 ;
X = 8 ;

我是一个完整的初学者,我不知道我做错了什么.

I'm a complete beginner and I don't know what I am doing wrong.

推荐答案

这是一个使用 nth0/4(或 select/3 正如@false 指出的那样):

Here is a simple solution using nth0/4 (or select/3 as pointed out by @false):

unique(X, L) :-
    nth0(_, L, X, R),
    \+ member(X, R).

nth0/4 第 4 个参数 R 是删除了元素 X 的列表 L.然后我们只需检查 X 不在 R 中.

nth0/4 4th argument R is the list L with the element X removed. We simply check then that X is not in R.

unique(X, L) :-
    nth0(_, L, X, R),
    maplist(dif(X), R).

这解决了@false 指出的问题,但由于您是初学者,我怀疑您对此是否感兴趣.

This fixes the problem pointed out by @false, though since you are a beginner I doubt this is of much interest to you.

这具有在以下情况下工作的优势:

This has the advantage of working in situations like this one:

?- unique(b, [X, Y, a]).
X = b,
dif(Y, b) ;
Y = b,
dif(X, b) ;
false.

这篇关于在列表中查找唯一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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