I have a homework assignment in Prolog which i just can't solve.
I have a Prolog predicate, listsum(L,S), which will succeed if L is a list of sequential numbers and S is the sum of this list.
So the code must respond to these queries like this:
?- listsum(L,6).
L = [1, 2, 3] ;
false.
?- listsum(L,45).
L = [1, 2, 3, 4, 5, 6, 7, 8, 9] ;
false.
?- listsum(L,46).
false.
As you can see the sum can only be true if it can be 'made' by a selection of sequential numbers, which have to start at 1. We could use a predicate we made in a previous assignment which i have already completed:
fromTill(X,X,[X]):-!.
fromTill(L,H,[L|Xs]):-
integer(L),
integer(H),
L=<H,
Z is L+1,
fromTill(Z,H,Xs).
fromTill(L,H,[L|Xs]):-
integer(L),
integer(H),
L>=H,
Z is L-1,
fromTill(Z,H,Xs).
This fromTill predicate will give the list of numbers between two integers. So:
?-fromTill(1,8,X)
X = [1,2,3,4,5,6,7,8]
So i don't know where to begin with this assignment. My first thought was to use an accumulator which will determine the sum of the list. Then the fromTill predicate will determine if the list is sequential which will be included in the final listSum preedicate. So, so far i have this but i have no idea where to go next:
listsumAcc([], 0).
listsumAcc([H|T], N):-
listsumAcc(T, N1),
N is N1 + H.
Let me know if you could help me out! It would be greatly appreciated.