logical - Prolog - intern variables sum -


i'm having trouble trying sum lists have.

i'm having:

[[[_g8511,0,1,_g8520],[_g8526,1,0,0],[_g8541,_g8544,0,1]],  [[1,1,1,_g8568],[0,1,0,1],[0,_g8592,0,1]],  [[1,0,_g8613,_g8616],[0,1,_g8628,0],[0,_g8640,_g8643,1]]] 

my problem try sum elements inside list. know how iterate through it, need either ignore intern variables, or make them 0.

i tried using sum_list(list, sum), figured can not handle intern variables. question how can either ignore elements not having value of 0 or 1, or how can make internal variables 0?

you use nonvar/1 predicate succeeds when argument not variable.

you write sum_list predicate:

sum_list(list,sum):-flatten(list,list2),sum_list2(list2,sum).  sum_list2([],0). sum_list2([h|t],sum):- var(h),sum_list2(t,sum). sum_list2([h|t],sum):- nonvar(h), sum_list2(t,sum1),sum sum1+h.   

note in above solution since need sum , lists nested used flatten/2 predicate flatten nested list flat list.

?- sum_list([[[_g8511,0,1,_g8520],[_g8526,1,0,0],[_g8541,_g8544,0,1]],[[1,1,1,_g8568],[0,1,0,1],[0,_g8592,0,1]],[[1,0,_g8613,_g8616],[0,1,_g8628,0],[0,_g8640,_g8643,1]]],sum). sum = 12 ; false. 

another solution (deterministic) using foldl/4 be:

add(x,y,sum):- (nonvar(x)-> sum x+y;sum y).  sum(list,sum):- flatten(list,l2),foldl(add,l2,0,sum).  

Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -