[英]Prolog - Add list numbers
I am trying to solve some prolog exercises in order to learn the language and i have problem adding the numbers in a prolog list. 我正在尝试解决一些序言练习,以学习该语言,并且在序言列表中添加数字时遇到问题。
For example i have the list [1,2,3] and i want to have as output number 6. 例如,我有列表[1,2,3],而我想将其作为输出数字6。
I wrote this code but it is not working. 我写了这段代码,但是没有用。
list_adder([H|T],S):- S is H + T.
can anyone explain why? 有谁能解释为什么?
try this: 尝试这个:
list_adder([ ],0).
list_adder([X|L],Sum) :- list_adder(L,SL), Sum is X + SL.
It's because H + T
in the example is matched with 1 + [2, 3]
, which doesn't mean anything. 这是因为示例中的
H + T
与1 + [2, 3]
匹配,这没有任何意义。 You should process the [2, 3]
further, as shown in Fourth's answer. 您应该进一步处理
[2, 3]
,如Third的答案所示。
list_adder(L,X),
list_adder(L,[],X).
list_adder([],L,X) :-
length(L,X).
list_adder([N|R1],L1,X) :-
length(L,N),
append(L1,L,L2),
list_adder(R1,L2,X).
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.