Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a list in Prolog

I'm developing an application written in Prolog. I get to a point in which I want to filter a list of elements and remove those which do not meet a certain constraints or conditions, keeping the original list order. I thought the best way for doing it would be something like this:

filter([],Filtered).
filter([L|List],[F|Filtered]) :-
    /* Conditions are met: bypass the element to the filtered list */
    check_conditions(L),
    filter(List,Filtered).
filter([L|List],Filtered) :-
    /* Conditions are not met: do not include the element in the filtered list */
    filter_aborts(List,Filtered).

Before accepting it as a solution to my problem I wanted to give it a try (independently), so I compiled and run my code (SWI-Prolog) and tested a few situations. When I type in the Prolog query using a hard-coded list (or whatever you want to call it) I get what something like this:

?- filter([id01,id02,id03,id04,id05,id06],F).
F = [id03, id05, id06|_G1024] .

The list is certainly filtered but I get this instance name "_G1024" at the end of it. I understand this happens because F is not instantiated, but I don't know what would be the solution. Moreover, if I try to do something different like entering the list as an instantiated variable, what I get is even more strange:

?- L=[id02,id03,id04,id05,id06].
L = [id02, id03, id04, id05, id06].

?- filter(L,F).
L = [] ;
L = [id01],
F = [id01|_G347] ;
L = [id01, id01],
F = [id01, id01|_G403] 
... and so on.

Aren't Prolog variables supposed to be assign-once variables? Does my program actually change L or I am not understanding it correctly? A part from that, since I am new to Prolog, I would appreciate any comment regarding my Prolog -let's say...- "style".

like image 673
Carles Araguz Avatar asked Feb 26 '26 21:02

Carles Araguz


1 Answers

You use SWI-Prolog, so you can write a predicate which succeeds or fails according to your conditions, then use include(Predidate, Lst, Success) . For axample

include(check_conditions,Lst, Success)
like image 54
joel76 Avatar answered Mar 02 '26 13:03

joel76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!