I just started learning about prolog and i'm thoroughly confused.
Consider the following scenario: I have a knowledge base that contains facts about a person, with the format person(Name,age).
Example:
person(brad,20).
person(lindsey,15).
person(sophie,18).
person(charles,24).
I want to create a rule that would evaluate to true when the sum of the ages exceed 40. Furthermore, if queried, it would output/display the names of the people whose ages adds up to 40. So, i tried this:
addsto40(X,Y,Sum) :- person(X,A), person(Y,B), Sum is A + B, Sum > 9.
When i query the following it return the names of two people whose ages add up to a number larger than 40. (i hit ; to get all the solutions). Example of query:
?- addsto40(X,Y,Sum).
this query returns the follwing:
X = brad,
Y = charles,
Sum = 44 ;
X = sophie,
Y = charles,
Sum = 42 ;
X = charles,
Y = brad,
Sum = 44 ;
X = charles,
Y = sophie,
Sum = 42 ;
X = Y, Y = charles,
Sum = 48.
but, this restricts the output to pairs of two. I wanted it to not have a restriction so, the answer could include for example: brad,lindsey, and sophie.
I tried a number of unsuccessful solutions. I thought about implementing addsto40/3, then adding one person until sum reaches 40. However, it's not working the way i want it to work.
addsto40(X,Y,Sum) :- person(X,A), person(Y,B), Sum is A + B, Sum < 40, addper(P,Sum,Newsum).
addsto40(X,Y,Sum) :- person(X,A), person(Y,B), Sum is A + B, Sum > 40.
addper(Y,Sum,Newsum) :- person(Y,X), Newsum is Sum + X, Newsum < 40, addper(P,Newsum,someSum).
addper(Y,Sum,Newsum) :- person(Y,X), Newsum is Sum + X, Newsum > 40.
Could I be guided into the right direction please? Why is this not working? Does the solution lie in implementing a list somehow? Do you have any tips or tricks for prolog beginners? I appreciate any kind of help. Thank you?