简体   繁体   中英

Sum of list elements sums| Prolog

I'm trying to sum the results of list elements 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?

The code you posted should have given you singleton warnings when consulted on your prolog interpreter. Prolog is case sensitive. Furthermore, List1 , which starts with a upper case letter, is a variable and list1 , which starts with a lower case letter, is an atom. So in your code you should have been warned that List1 , List2 and Result2 are singleton variables (appear only once in the procedure).

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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