Home > Enterprise >  Collect data, but skip non-zero referenced-data
Collect data, but skip non-zero referenced-data

Time:04-22

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].

CodePudding user response:

How about adding a case for 0 and a case for non-zero:

fnf([],[],[]).

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

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

or

pairs_keys_values(Pairs, Rs, Cs),
findall([RH,CH], (member(RH-CH, Pairs), get(RH, CH, 0)), F).

CodePudding user response:

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.

  • Related