PROLOG -sum元素

时间:2013-10-28 06:22:15

标签: matrix prolog

  

块引用

我有m x n矩阵n,m> 1:找到和角元素ex [1 5 2] [3 6 4] sum = 1 + 2 + 3 + 4

  

块引用

1 个答案:

答案 0 :(得分:0)

您可以尝试使用累加器。我们逐行遍历矩阵。

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).