块引用
我有 mxn 矩阵 n,m>1:find sum angular elements ex [1 5 2] [3 6 4] sum =1+2+3+4
块引用
你可以试试这个使用累加器。我们逐行遍历矩阵。
sum_of_corners(M, S) :-
% the current value of the accumulator is 0
sum_of_corners(M, 0, S).
% when the travel is finished
sum_of_corners([], T, T).
% We work with the current line
sum_of_corners([L | RL], T1, T) :-
% We get the first element
L = [C | R],
% we compute the sum of the extremities of the line
sum_of_extremities(R, C, T2),
T3 is T1+T2,
% we keep on with the rest of the matrix
sum_of_corners(RL, T3, T).
% we have found the last element of the line
sum_of_extremities([Last], T1, T) :-
T is T1 + Last.
% we ignore the current element wich is not the last
sum_of_extremities([_ | R], T1, T) :-
sum_of_extremities(R, T1, T).