Search code examples
prolog

Last member of a list is a memory position


I don't understand why with this predicate the last position is a memory position.

elimina_diretos(_,[],_).
elimina_diretos(LA,[H|T],LP):-
    member(H,LA),
    elimina_diretos(LA,T,LP).
elimina_diretos(LA,[H|T],[H|LP]):-
    elimina_diretos(LA,T,LP).

If I type

?- elimina_diretos([tiago,andre],[pedro,tiago,rocha,andre],L).

Prolog gives me:

L = [pedro, rocha|_G609] ;

how can I clean that _G609?


Solution

  • First change:

    elimina_diretos(_,[],[]).
    

    Note that your code must be made deterministic, or you'll get unwanted 'solutions' on backtracking:

    ?- elimina_diretos([tiago,andre],[pedro,tiago,rocha,andre],L).
    L = [pedro, rocha] ;
    L = [pedro, rocha, andre] ;
    ...
    

    Then the second change (note the cut):

    elimina_diretos(LA,[H|T],LP):-
        memberchk(H,LA),!,
        elimina_diretos(LA,T,LP).
    

    Now should work as you expect

    ?- elimina_diretos([tiago,andre],[pedro,tiago,rocha,andre],L).
    L = [pedro, rocha] ;
    false.
    

    Use memberchk/2 instead of member/2, it's far more efficient.