Search code examples
prolog

Generate a liste containing all the instances of a variable


i am trying to generate a list in Prolog that contains all the instances of a variable. for exemple:

entree( 'foie gras' ).
entree( 'salade gourmande' ).
entree( 'crudites' ).

generateliste(E,L)//L should be L=["foie gras','salade gourmande,'crudites'] 

I tried this:

generateliste(E,[E|R]):-entree(E),not(member(E,R)),generateliste(E,R).

but i know it won't work because there is no base case to stop the recursion , can anyone help me please?


Solution

  • Beside the missing base case, you have a more fundamental problem.

    not(member(E,R)) will never succeed, regardless the actual value of E, if R is a variable. Then you have to 'reverse the information flow', and keep a temporary list (called Acc here) to check for already collected items:

    generateliste(Acc,[E|R]) :-
        entree(E),
        not(member(E,Acc)),
        generateliste([E|Acc],R).
    generateliste(_,[]).
    
    

    Call it in this way

    ?- generateliste([],L).
    L = ['foie gras', 'salade gourmande', crudites] .
    

    but remember the savy hint you got from Peter and brebs: you should study the library findall/3, setof/3 and bagof/3 builtins.