Prolog:检查列表中的重复项 [英] Prolog: check against duplicates in a list

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

问题描述

  1. 写一个谓词allDistinct/1,该谓词的参数是一个(符号)列表,并且如果列表中的所有符号都不相同,则该谓词将成功.

  1. Write a predicate allDistinct/1 whose parameter is a list (of symbols) and which succeeds if all symbols in the list are different.

notin(A,[]).
notin(A,[B|C]) :-
   A\=B,
   notin(A,C).

allDistinct([]).
allDistinct([_]).
allDistinct([A|B]) :-
   notin(A,B), 
   allDistinct(B).

推荐答案

紧跟@whd之前的草图我们可以这样进行.

Following up on the previous sketch by @whd we can proceed like this.

基于 iwhen/2 ,我们可以像这样简单地定义distinct/1:

:- use_module(library(lists), [same_length/2]).

distinct(Es) :-
   iwhen(ground(Es), (sort(Es,Fs),same_length(Es,Fs))).

使用SICStus Prolog 4.5.0进行示例查询:

Sample queries using SICStus Prolog 4.5.0:


| ?- distinct([1,2,3]).
yes
| ?- distinct([1,2,3.0]).
yes
| ?- distinct([1,2,3.0,2]).
no
| ?- distinct([1,2,3.0,X]).
! error(instantiation_error,_283)

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

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