databaseprologvisual-prologprolog-findall

Prolog - The same functioning but with no findall


Does anyone know how I could implement I predicate doing what this one does but without "findall"? Thank you a lot.

domains
    oferta =  rebaixat ; normal
    element = string
        list = element*
database
    producte (string, integer, oferta)
predicates
    nondeterm reduced2(list)

clauses

    producte("Enciam",2,rebaixat). 
    producte("Peix",5,normal).
    producte("Llet",1,rebaixat). 
    producte("Formatge",5,normal).

         reduced2(Vals):-
            findall(Val, producte(Val,_,rebaixat),Vals).
Goal
    write("Amb findall"),nl,
    reduced2(List).

Solution

  • I don't know much about Visual Prolog, but I will try to give a general answer. It depends on whether you want to find a findall/3 replacement for a specific case or in general, though.

    In the specific case, you can use an accumulator. In your case, this would be a list into which the values are added as you find them. Something like:

    acc(In, List) :-
       ... % do something to generate possible next value
       ... % test if value is already in list In
       !,
       Out = [Val|In], % adds to the head, but is faster than using append
       acc(Out, List).
    acc(List, List).
    

    I.e., when you can't find another possible value, you return the list of values that you found. Note that this may be slow if you have to accumulate a lot of values and generating the next possible value is done via backtracking. Also, this will not let you generate duplicates, so it's not an exact replacement for findall/3.

    If you want a general replacement for findall/3, where you can specify a goal and a variable or term that will contain the instance to be accumulated, then you won't get around using some sort of non-logical global variable. After finding the next value, you add it to what's been stored in the global variable, and cause backtracking. If generating the next value fails, you retrieve the content of the global variable and return it.