简体   繁体   English

列表元素之和 sums| 序言

[英]Sum of list elements sums| Prolog

I'm trying to sum the results of list elements sum.我正在尝试对列表元素 sum 的结果求和。 I have this code:我有这个代码:

adding_lists(List1, List2, Result) :- sumlist(list1, Result1), sumlist(list2, Result1), Result is Result1 + Result2.

but it returns false, what it's the way for this sum?但它返回false,这个总和的方式是什么?

The code you posted should have given you singleton warnings when consulted on your prolog interpreter.在您的 prolog 解释器上咨询时,您发布的代码应该会给您单例警告。 Prolog is case sensitive. Prolog 区分大小写。 Furthermore, List1 , which starts with a upper case letter, is a variable and list1 , which starts with a lower case letter, is an atom.此外,以大写字母开头的List1是一个变量,而以小写字母开头的list1是一个原子。 So in your code you should have been warned that List1 , List2 and Result2 are singleton variables (appear only once in the procedure).所以在你的代码中你应该被警告List1List2Result2是单例变量(在过程中只出现一次)。

Aside from that, you are issuing two calls to sumlist/2 (presumably for List1 and List2 and unifying the result with the same variable Result1 , whereas the second call should use Result2 ).除此之外,您正在向sumlist/2发出两次调用(大概是针对List1List2并将结果与​​相同的变量Result1统一,而第二次调用应使用Result2 )。

After fixing those issues you will end up with this code:解决这些问题后,您将得到以下代码:

adding_lists(List1, List2, Result) :-
  sumlist(List1, Result1),
  sumlist(List2, Result2),
  Result is Result1 + Result2.

that should work fine.那应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM