且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

列表列表中是否存在元素?

更新时间:2022-05-27 22:04:51

问题在于,[[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).