PROLOG:如果顺序无关紧要,则确定列表中的元素是否相等 [英] PROLOG: Determining if elements in list are equal if order does not matter

查看:67
本文介绍了PROLOG:如果顺序无关紧要,则确定列表中的元素是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出一种方法来检查两个列表是否相等,而不管它们的元素顺序如何.

I'm trying to figure out a way to check if two lists are equal regardless of their order of elements.

我的第一次尝试是:

areq([],[]).
areq([],[_|_]).
areq([H1|T1], L):- member(H1, L), areq(T1, L).

然而,这只检查左边列表的所有元素是否都存在于右边的列表中;意思 areq([1,2,3],[1,2,3,4]) =>真的.在这一点上,我需要找到一种能够在双向意义上测试事物的方法.我的第二次尝试如下:

However, this only checks if all elements of the list on the left exist in the list on the right; meaning areq([1,2,3],[1,2,3,4]) => true. At this point, I need to find a way to be able to test thing in a bi-directional sense. My second attempt was the following:

areq([],[]).
areq([],[_|_]).
areq([H1|T1], L):- member(H1, L), areq(T1, L), append([H1], T1, U), areq(U, L).

我会尝试重建左边的 les 并最终交换列表;但这次失败得很惨.

Where I would try to rebuild the lest on the left and swap lists in the end; but this failed miserably.

我的递归感极差,根本不知道如何改进,尤其是使用Prolog.在这一点上,任何提示或建议将不胜感激.

My sense of recursion is extremely poor and simply don't know how to improve it, especially with Prolog. Any hints or suggestions would be appreciated at this point.

推荐答案

使用 sort/2 ISO 标准内置谓词的简单解决方案,假设两个列表都不包含重复元素:

A simple solution using the sort/2 ISO standard built-in predicate, assuming that neither list contains duplicated elements:

equal_elements(List1, List2) :-
    sort(List1, Sorted1),
    sort(List2, Sorted2),
    Sorted1 == Sorted2.

一些示例查询:

| ?- equal_elements([1,2,3],[1,2,3,4]).
no

| ?- equal_elements([1,2,3],[3,1,2]).    
yes

| ?- equal_elements([a(X),a(Y),a(Z)],[a(1),a(2),a(3)]).
no

| ?- equal_elements([a(X),a(Y),a(Z)],[a(Z),a(X),a(Y)]).
yes

这篇关于PROLOG:如果顺序无关紧要,则确定列表中的元素是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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