'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 1:[1]
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.
Solution 2:[2]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gusbro |
| Solution 2 | TessellatingHeckler |
