Prolog-从列表中删除具有相同第一个值的对 [英] Prolog - deleting pairs with the same first value from list

查看:140
本文介绍了Prolog-从列表中删除具有相同第一个值的对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的对象列表

list([obj(x,y),obj(x,z),obj(a,b),obj(b,c)]).

并且我想删除那些具有相同第一个值的元素,因此我可以使用修改后的列表.在这种情况下,最终列表将如下所示:

and i would like to remove those elements that share the same first value, so i can work with the modified list. In this case the final list would look like this

list([obj(a,b),obj(b,c)]

有人可以帮忙吗?我真的很为此挣扎.

Could anyone help please? I am really struggling with this one.

推荐答案

让我们从测试开始吧!

% Testing

:- begin_tests(collapse).   

test(one)   :- collapse([],[]).
test(two)   :- collapse([obj(a,b)],[obj(a,b)]).
test(three) :- collapse([obj(a,b),obj(b,c)],
                        [obj(a,b),obj(b,c)]).                        
test(four)  :- collapse([obj(a,b),obj(a,c),obj(b,j)],
                        [obj(b,j)]).
test(five)  :- collapse([obj(a,b),obj(a,c),obj(b,j),obj(a,x),obj(b,y)],
                        []).
test(six)   :- collapse([obj(a,b),obj(a,c),obj(b,j),obj(b,y),obj(c,x)],
                        [obj(c,x)]).

:- end_tests(collapse).

rt :- run_tests(collapse).

然后输入代码:

% This is called

collapse(Lin,Lout) :- collapse(Lin,[],Lout).

/*
 * Helper predicate:
 * collapse(List_over_which_we_recur_getting_smaller,
 *          Elements_which_we_have_already_seen,
 *          List_which_collects_the_result_going_down,
 *          List_which_collects_the_result_coming_up).
 */

collapse([],_Filter,[]).  % base case, kick a [] upwards; don't care about Filter

collapse([obj(A,_)|Objs],Filter,Lup) :- 
   (member(obj(A,_),Objs);member(obj(A,_),Filter)),     % Does the obj(A,_) appear elsewhere (in Filter or Objs)?
   !,                                                   % Commit to this execution path where obj(A,_) is not unique
   (member(obj(A,_),Filter)                             % Slight improvement: add obj(A,_) to "Filter" only it it's not yet in there
       -> NewFilter = Filter
       ;  NewFilter = [obj(A,_)|Filter]),
   collapse(Objs,NewFilter,Lup).                        % Do not retain obj(A,_)

collapse([obj(A,X)|Objs],Filter,Lup) :- 
   \+(member(obj(A,_),Objs);member(obj(A,_),Filter)),   % Does the obj(A,_) appear elsewhere (in Seen or ToSee)?
   !,                                                   % Commit to this execution path where obj(A,_) IS unique   
   collapse(Objs,Filter,Ltmp),                          % Filtering the rest of Objs, which defines Ltmp      
   Lup = [obj(A,X)|Ltmp].                               % DO retain object on the way up, correctly ordering result.

好的,所以:

?- rt.
% PL-Unit: collapse ...... done
% All 6 tests passed
true.

这篇关于Prolog-从列表中删除具有相同第一个值的对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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