Question about difference lists
- From: "John Poplett" <john.poplett@xxxxxxxxx>
- Date: 24 Aug 2005 19:26:25 -0700
Hi.
I am teaching myself prolog. As an exercise, I wrote a predicate
"unique" to find all the unique elements in a list. I wrote a version
with an accumulator and made an attempt to write an equivalent
predicate using difference lists. I was motivated to use difference
lists to learn them better and to avoid having to reverse the list at
the end of the computation.
The difficulty is that I use member/2 to decide if I can safely discard
an element by testing if it is already part of the output. With
difference lists, the member/2 predicate will find a variable in the
difference list and bind to it. This causes the evaluation to fail.
Below is some sample code that demonstrates what I am trying to explain
here.
Thanks for any suggestions.
John
% uniq_acc works
uniq_acc(List,Set) :- uniq_acc(List,[],Set1), reverse(Set1, Set).
uniq_acc([],A,A).
uniq_acc([Head|Tail],Acc,Result) :-
member(Head,Acc),
!,
uniq_acc(Tail,Acc,Result).
uniq_acc([Head|Tail],Acc,Result) :-
uniq_acc(Tail,[Head|Acc],Result).
% uniq_dl fails in the call to member below
uniq_dl(List,Set) :- uniq_dl(List,Set,[]).
uniq_dl([],Slot,Slot).
uniq_dl([Head|Tail],Set,Slot) :-
member(Head,Set), % trouble is here.
!,
uniq_dl(Tail,Set,Slot).
uniq_dl([Head|Tail],[Head|Slot1],Slot) :-
uniq_dl(Tail,Slot1,Slot).
.
- Follow-Ups:
- Re: Question about difference lists
- From: Bart Demoen
- Re: Question about difference lists
- Prev by Date: Re: I now realize WHY my 'consistency check' was pointless: CLP.
- Next by Date: Re: I now realize WHY my 'consistency check' was pointless: CLP.
- Previous by thread: ISO Prolog Document
- Next by thread: Re: Question about difference lists
- Index(es):
Relevant Pages
|
|