Prolog - 矩阵中行的总和
一个 nxn 矩阵可以表示为 n 个列表的列表,每个列表有 n 个元素, 矩阵实际上可以 1 2 3 4 5 6 7 8 9 写为 [[1, 2, 3], [4, 5, 6], [7, 8, 9]]。
我需要编写一个 Prolog 程序来添加每个 ROW 中的所有值。 我是 Prolog 新手,请帮忙。 提前致谢!
以下是我所做的,但似乎不起作用......
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).
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, but 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要计数器
I
和J
。只需边走边解压列表即可。下面是 rowTotal 的解决方案:以下尾递归解决方案有点难以理解,但效率更高:
应用相同的技术来实现
sum
和result
。You don't need counters
I
andJ
. Simply unpack the lists as you go. Here's a solution for rowTotal:The following tail-recursive solution is a little trickier to get your head around, but is more efficient:
Apply the same technique to implement
sum
andresult
.