Search code examples
listprolog

Collect data, but skip non-zero referenced-data


i have the following

fnf([],[],[]).
fnf([RH|RT],[CH|CT],[[RH,CH]|Res]) :- get(RH,CH,V), V == 0, fnf(RT,CT,Res).

i'm trying to collect only elements of Cs and Rs for which the V is zero. The code above does that but fails when it hits non-zero value. I want to just skip them, instead of failing the whole goal.


this sort of works

fnf([RH|RT],[CH|CT],[[RH,CH]|Res]) :- get(RH,CH,V), ( V == 0 -> fnf(RT,CT,Res);true).

still _2044 !! should not be there

F = [[1, 1], [2, 2]|_2044].

Solution

  • If you want to test only once (get/3 + condition) and then keep the item or skip it and continue recursion you can use an if-then-else construct like so:

    fnf([], [], []).
    fnf([RH|RT], [CH|CT], Res) :-
        get(RH, CH, V),
        (   V==0                  % test
        ->  Res=[[RH, CH]|Res1]   % condition met, keep item
        ;   Res=Res1              % condition not met, skip item
        ),
        fnf(RT, CT, Res1).
    

    Also note the call to get/3 may backtrack if it leaves choicepoints.