The best way to localize the problem is to simplify your request first:
?- sum([0],S). true ?- sum([],S). true
Even for those, you get an answer that any S will do. how
?- sum([],s(s(0))). yes
Since [] can only be handled by your fact, the error should be in this very fact. You stated:
sum([], Sum).
This means that the sum [] is just something. You probably meant 0.
Another error is hidden in the last rule ... After fixing the first error, we get
?- sum([0],Sum). Sum = 0 ?- sum([s(0)],Sum). no
Here the last question is responsible. It reads:
sum([s(X)|Xs], Sum):-sum([X|Xs],s(Sum)).
Recursive rules are relatively difficult to read in Prolog. The easiest way to understand them is to look at :- and understand that it should be an arrow and a lar; (thus, arrow from right to left), which means:
provided that the goals on the right are true
, we conclude that is on the left side
Thus, compared to informal recording, arrows point in the opposite direction!
For our query, we can consider the following instance, substituting Xs with [] and X with 0.
sum([s(0)| [] ], Sum) :- sum([0| []],s(Sum)).
So, this rule is now read from right to left: Provided that sum([0],s(Sum)) is true, ... However, we know that only sum([0],0) is fulfilled, but not the target. Therefore, this rule never applies! What you intended was rather the opposite:
sum([s(X)|Xs], s(Sum)):-sum([X|Xs],Sum).