[mercury-users] New to mercury: structure reuse and efficiency

Peter Schachte schachte at cs.mu.OZ.AU
Thu Jul 1 11:36:43 AEST 2004

Gregory D. Weber wrote:

>There's an implied question here which I don't think has been answered:
>how _does_ he do what he wants to do here, which, I believe, is to
>make sure that H does not equal T before making the recursive call?
> > member([H|T], H).
> > 
> > member([H|T], X) :- not(X=H), member(T, X).
I think the best answer to your question is:  you don't, the compiler 
does it for you.  This definition does what he wants:

member([H|T], H).

member([_|T], X) :- member(T, X).

In fact, it's better than what he's asking for, because the compiler 
does it in a more flexible way than you could do it yourself.  The 
compiler is smart enough to notice a call member(L, X) where L and  X 
are both sure to be ground, and it forces the call to be deterministic 
for you, so you don't try to see if the element is in the tail of the 
list when you've already seen that it matches the head.  However, when X 
is unbound, then it will match every element of the list, so you don't 
want to commit yourself to the first match.  Consider this predicate to 
determine whether two lists have any elements in common:

    overlap(L1, L2) :- member(L1, X), member(L2, X).

Here the first call to member will have X unbound and the second will 
have it bound, so the first must not commit to the first match (because 
it may not be the first elment of L1 that appears on L2), but the second 
one can (because we don't care how many times an element of L1 appears 
on L2).  But further, once we find an element in common, we can commit 
to that, because we don't care which elements are in common, just that 
at least one is.  The Mercury compiler will do all that for you without 
you having to say anything.

Peter Schachte              640K should be enough for anyone!
schachte at cs.mu.OZ.AU            -- Bill Gates, 1981
Phone: +61 3 8344 1338     

mercury-users mailing list
post:  mercury-users at cs.mu.oz.au
administrative address: owner-mercury-users at cs.mu.oz.au
unsubscribe: Address: mercury-users-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-users-request at cs.mu.oz.au Message: subscribe

More information about the users mailing list