Prolog - 在列表列表中列出元素 [英] Prolog - List elements in a list of lists

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

问题描述

我有一个列表和一个列表列表:

I have a list and a list of lists:

A = [1,2,4,5]
L = [[1,2,5],[3,4,5]]

如果 A 包含与列表之一相同的元素,我希望它返回 true.由于 A 包含与 L ([1,2,5]) 中的第一个列表相同的元素 (1,2,5),即使 A 中的一个元素不在 L 的第一个列表中,它也应该返回 true.

If A contains the same elements as one of the lists, I want it to return true. As A contains the same elements (1,2,5) as the first list in L ([1,2,5]), it should return true even though there's one element in A that isn't in the first list in L.

我尝试使用 a 类似问题的答案中提供的几个谓词 为了解决这个问题:

I've tried using a couple of predicates supplied in the answer of a similar question in order to solve this:

p(X):- findall( Y, (member(Y,X), \+ have_common_element(X,Y) ), [_]).
have_common_element(A,B):- member(X,A), memberchk(X,B).

但是以下查询将返回 false:

However the following query will return false:

p([[[1,2,5],[3,4,5]],[1,2,4,5]]).

我知道这是因为 A (4) 中有一个元素不在 L 的第一个列表中,尽管我很难弄清楚如何扩展谓词以使查询返回 true.

I understand that this is because there is an element in A (4) that isn't in the first list of L, although I'm having difficulty figuring out how to extend the predicates to have the query return true.

是否可以扩展这些谓词,以便即使包含额外的(和非相互的)元素也会返回 true?

Would it be possible to extend these predicates so that true will be returned even with the additional (and non-mutual) element included?

推荐答案

你想说的好像是:

p(A, Ess) :-
   member(Es, Ess), % there is a list Es in Ess
   maplist(A+\E^member(E,A), Es). % for all E in Es: member(E,A).

或不使用 lambda:

or without lambdas:

p(A, Ess) :-
   member(Es, Ess),
   maplist(list_member(A), Es).

list_member(L, E) :-
   member(E, L).

这篇关于Prolog - 在列表列表中列出元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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