Prolog - sum of row in matrix
An n x n matrix can be represented as a list of n lists, each with n elements, the matrix could actually 1 2 3 4 5 6 7 8 9 written as [[1, 2, 3], [4, 5, 6], [7, 8, 9]].
I need to write a Prolog program to add all the values in each ROW. I am new in Prolog, please help. Thanks in advanced!
Below is what I had done, 开发者_如何学JAVAbut it seems like not working....
sum(X):-
result(X,0,0,Y),!.
result([H|T],I,J,Length):-
rowTotal([H|T],J,Sum),
write('Sum of Row: '),
write(Sum),nl,
(not(I = Length)) ->
(NewI is I + 1,
result([H|T],NewI,0,Length);!).
rowTotal([H|T],J,Sum):-
rowValue(H,J,Value),
rowTotal(T,NewSum),
Sum is Value + NewSum.
rowTotal([],0).
rowValue([H|T],J,Value):-
(J < 3) ->
Value = H,
NewJ is J+1,
rowValue([H|T],NewJ,Value).
You don't need counters I
and J
. Simply unpack the lists as you go. Here's a solution for rowTotal:
rowTotal([], 0).
rowTotal([H|T], Sum) :-
rowTotal(T, SubTotal),
Sum is H + SubTotal.
The following tail-recursive solution is a little trickier to get your head around, but is more efficient:
rowSum(L, Sum) :-
rowResult(L, 0, Sum).
rowResult([], Acc, Acc).
rowResult([H|T], Acc, Sum) :-
S is H + Acc,
rowResult(T, S, Sum).
Apply the same technique to implement sum
and result
.
精彩评论