我在Prolog中有此数据库:
family(person( john, cohen, date(17,may,1990), unemployed), person( lily, cohen, date(9,may,1990), unemployed),[ ] ).
family(person( john, armstrong, date(7,may,1988), unemployed), person( lily, armstrong, date(29,may,1961), unemployed), [ ] ).
family(person( eric, baily, date(7,may,1963), works( bbc, 2200)), person( grace, baily, date(9,may,1965), works( ntu, 1000)), [person( louie, baily, date(25,may,1983), unemployed) ] ).
family(person( eric, baily, date(7,may,1963), works( acc, 21200)), person( grace, baily, date(9,may,1965), works( ntnu, 12000)), [person( louie, baily, date(25,may,1983), unemployed) ] ).
family(person( eric, fox, date(27,may,1970), works( bbc, 25200)), person( grace, fox, date(9,may,1971), works( ntbu, 13000)), [person( louie, fox, date(5,may,1993), unemployed) ] ).
husband(X) :- family(X, _, _).
wife(X) :- family(_, X, _).
child(X) :- family(_, _, Children), member(X, Children).
salary(person(_, _, _, works(_, S)), S).
salary(person(_, _, _, unemployed), 0).
格式为: 家庭(丈夫,妻子,[孩子])。 家庭中的每个人都有名字,姓氏,出生日期,工作和薪水。
我有一项作业,要求我编写以下规则:
1)编写一个序言规则“ totalIncome / 2”来计算一个家庭的总收入。
2)编写序言查询以打印每个家庭的总收入。
我能够从清单中获得丈夫的薪水,并从另一个清单中获得妻子的薪水。
salaries(L) :- findall(X,family(person(_,_,_,works(_,X)),_,_),L).
salaries(L2) :- findall(X,family(_,person(_,_,_,works(_,X)),_),L2).
我似乎无法解决这个问题,因此感谢您的帮助。谢谢
答案 0 :(得分:1)
您正在寻找一个扭曲的方向...我不应该计算不同家庭的薪水,例如妻子的薪水,但是一个家庭的薪水,这是我的实现方式:
add(X,Y,Sum):- Sum is X+Y.
sum(Xs,Sum):- foldl(add,Xs,0,Sum).
totalIncome(family(X,Y,T), Income):-
family(X,Y,T),maplist(getSalary,[X,Y|T], L), sum(L,Income).
getSalary(person(_,_,_,works(_,X)), X).
getSalary(person(_,_,_,unemployed), 0).
示例:
?- totalIncome(X,P).
X = family(person(john, cohen, date(17, may, 1990), unemployed), person(lily, cohen, date(9, may, 1990), unemployed), []),
P = 0 ;
X = family(person(john, armstrong, date(7, may, 1988), unemployed), person(lily, armstrong, date(29, may, 1961), unemployed), []),
P = 0 ;
X = family(person(eric, baily, date(7, may, 1963), works(bbc, 2200)), person(grace, baily, date(9, may, 1965), works(ntu, 1000)), [person(louie, baily, date(25, may, 1983), unemployed)]),
P = 3200 ;
X = family(person(eric, baily, date(7, may, 1963), works(acc, 21200)), person(grace, baily, date(9, may, 1965), works(ntnu, 12000)), [person(louie, baily, date(25, may, 1983), unemployed)]),
P = 33200 ;
X = family(person(eric, fox, date(27, may, 1970), works(bbc, 25200)), person(grace, fox, date(9, may, 1971), works(ntbu, 13000)), [person(louie, fox, date(5, may, 1993), unemployed)]),
P = 38200 ;
false.