列表列表中是否存在元素? [英] Does an element exists in a list of lists?

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

问题描述

我想查找给定元素是否存在于列表列表中.我只有在元素存在于某个位置是列表的第一个列表的情况下,我才变得正确.

I want to find if a given element exists in a list of lists. I am only getting true if the element exists somewhere is the first list of lists.

有什么建议吗?

memberlist(X,[[X|T1]|T2]).
memberlist(X,[[H|T1]|T2]) :-
  memberlist(X,[T1|T2]).

推荐答案

问题在于,[[H|T1]|T2]仅在给定 first 列表中至少包含一个元素的情况下匹配.确实:例如[[],[1,4],[2,5]]不会 [[H|T1]|T2]统一.

The problem is that [[H|T1]|T2] only matches given the first list has at least one element. Indeed: [[],[1,4],[2,5]] for instance does not unify with [[H|T1]|T2].

因此,您可以通过添加一个子句来解决该问题:

So you can solve the problem by adding a clause:

memberlist(X,[[]|T2]) :-
    memberlist(X,T2).

因此我们获得:

memberlist(X,[[X|_]|_]).
memberlist(X,[[H|T1]|T2]) :-
    memberlist(X,[T1|T2]).
memberlist(X,[[]|T2]) :-
    memberlist(X,T2).

第一个子句还使用下划线指定我们对这些变量不感兴趣".这在Prolog程序中很常见(可能是解释器警告说T1T2仅被提及一次).

the first clause also uses the underscores to specify that we are "not interested" in these variables. This is common for Prolog programs (probably the interpreter warned that T1 and T2 were mentioned only once).

因此,如果第一个列表用完了,我们只需移至下一个列表即可.

So in case the first list is exhausted, we simply move to the next list.

您的谓词会进行很多打包"和拆包".此外,我们可以使用member/2内置函数.所以我们可以重写它:

Your predicate does a lot of "packing" and "unpacking". Furthermore we can make use of the member/2 builtin. So we can rewrite it:

memberlist(X,[H|_]) :-
    member(X,H).
memberlist(X,[_|T2]) :-
  memberlist(X,T2).

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

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