打开列表和成员 [英] Open list and member

查看:43
本文介绍了打开列表和成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我想避免 append/3 的成本,所以我使用差异/开放列表.

Since I want to avoid cost of append/3, I use difference/open lists.

然而,开放列表的问题在于 member/2 通过将元素添加到尾部来对开放列表做出反应.例如:

The problem with an open list however is that member/2 reacts with an open list by adding the element to the tail. For example:

?- L=[a|_],member(b,L).
L = [a, b|_G1196] ;
L = [a, _G1195, b|_G1199] ;
L = [a, _G1195, _G1198, b|_G1202] ;
L = [a, _G1195, _G1198, _G1201, b|_G1205] ;
L = [a, _G1195, _G1198, _G1201, _G1204, b|_G1208] ;
L = [a, _G1195, _G1198, _G1201, _G1204, _G1207, b|_G1211] 

这是正确的行为,因为一个开放列表有一个无界的尾部",并且 member/2 函数将这个尾部/孔(变量)与成员的第一个参数统一起来.

This is correct behavior since an open list has an unbounded "tail" and the member/2 function unifies this tail/hole ( variable) with the first argument of member.

不过,我正在寻找一种方法,可以检查打开列表中是否存在与给定元素相等的元素.我该怎么做?

I'm looking however for a way I can check if there is an element in the open list that is equal to the given element. How can I do this?

推荐答案

您可以编写自己的 member/2 版本:member_open/2:

You could write your own version of member/2: member_open/2:

member_open(_,X) :-
    var(X),
    !,
    fail.
member_open(X,[X|_]).
member_open(X,[_|T]) :-
    member_open(X,T).

或更纯粹的方法:

member_open(X,Y) :-
    \+var(Y),
    Y = [X|_].
member_open(X,Y) :-
    \+var(Y),
    Y = [_|T],
    member_open(X,T).

谓词假设一个开放列表的尾部是var/1.如果谓词发现这样的尾部,则执行切割 (!) 并失败.

The Predicate makes the assumption that an open list has a tail that is var/1. If the predicate finds such a tail, it performs a cut (!) and fails.

演示:

?- member_open(a,[]).
false.

?- member_open(a,[a]).
true ;
false.

?- member_open(a,[a,a]).
true ;
true ;
false.

?- member_open(a,[a,a|_]).
true ;
true ;
false.

?- member_open(b,[a,a|_]).
false.

?- member_open(X,[X,a|_]).
true ;
X = a ;
false.

?- member_open(X,[c,a|_]).
X = c ;
X = a ;
false.

这篇关于打开列表和成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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