Prolog Have a list initialized to zero to use sum

2019-09-19 08:18发布

I want to have a predicate that has an empty list on the first iteration so

example(Lists,Result) :-

I need result to equal [], the very first time its used, Its a matrix and I want to continually add matrixes to it.

|a,b,c| |j,k,l| |s,t,u|
|d,e,f| |m,n,o| |v,w,x|
|g,h,i|.|p,q,r|,|y,z,?|

/*I want to be able to get back */
|(a+j+s),(b+k+t),(c+l+u)|
|(d+m+v),(e+n+w),(f+o+x)|
|(g+p+y),(h+q+z),(i+r+?)|

These are usually float values.

I need result to be [] the first time for my predicate to work. Is this possible? I know this is a confusing question and a long shot if you will understand it but any help would be great.

标签: prolog
1条回答
Luminary・发光体
2楼-- · 2019-09-19 09:04

Simple truth table. There are 8 possible combinations as you iterate over your list of lists, correct?

Try something like this:

foo( []     , []     , []     , []     ) .
foo( []     , []     , [Z|Zs] , [Z|Rs] ) :- R is 0+0+Z , foo( [] ,[] ,Zs , Rs ) .
foo( []     , [Y|Ys] , []     , [Y|Rs] ) :- R is 0+Y+0 , foo( [] ,Ys ,[] , Rs ) .
foo( []     , [Y|Ys] , [Z|Zs] , [R|Rs] ) :- R is 0+Y+Z , foo( [] ,Ys ,Zs , Rs ) .
foo( [X|Xs] , []     , []     , [R|Rs] ) :- R is X+0+0 , foo( Xs ,[] ,[] , Rs ) .
foo( [X|Xs] , []     , [Z|Xs] , [R|Rs] ) :- R is X+0+Z , foo( Xs ,[] ,Zs , Rs ) .
foo( [X|Xs] , [Y|Ys] , []     , [R|Rs] ) :- R is X+Y+0 , foo( Xs ,[] ,Zs , Rs ) .
foo( [X|Xs] , [Y|Ys] , [Z|Zs] , [R|Rs] ) :- R is X+Y+Z , foo( Xs ,Ys ,Zs , Rs ) .
查看更多
登录 后发表回答