I am writing a prolog program for a practice assignment where I would like to Write a predicate called sum(A,B,C) where A, B and C are lists of integers and prolog will return true if:
The elements in the concatenated list BC (i.e. lists B and C are “glued together”) form a permutation of the elements in A; and The sum of all integers in B equals the sum of all integers in C.
If anyone with more experience in prolog can give me some advice on how to get this done, that would be nice. I dont really know where to start. I would like to give an input like sum([1,2,3],[3,2,1],[2,3,1]). And prolog would return true. However, take, for example, sum([1,2,3],[4,5,6],[6,3,2]), this would return false since in this example lists 2 and 3 are not a different ordering(permutation) of the numbers of list1, and the sum of the integers in list 3 is not equal to the sum of the integers in list 2.
Any ideas or suggestions for the code?
I think you're overthinking it. :) Turn your specification into code directly and then work out the details:
sum(A, B, C) :-
append(B, C, BC),
permutation(A, BC),
sumlist(B, Sum),
sumlist(C, Sum).
This already reveals an ambiguity in your specification: you take care to explain that B and C must be concatenated to form a permutation of A, but that isn't the case for your example sum([1,2,3], [3,2,1], [2,3,1])
. If your code is closer to the truth than your words, your specification should instead be:
sum(A, B, C) :-
permutation(A, B),
permutation(A, C),
sumlist(B, Sum),
sumlist(C, Sum).
Now you're in luck because both sumlist/2
and permutation/2
already exist. So the program is complete and you haven't had to do anything yet except translate your natural language specification into a Prolog specification!
I should note though that there is no scenario where a permutation of a list will sum to a different value. At least, not in theory, and in practice, only if you are using floating point numbers would you find that to be the case.