2017-12-28 20 views
2

私はプロローグを使用して作成した関数を持っていて、何らかの理由で1つのリストではなく各要素に対して複数のリストを作成します。setofは1つのリストプロローグの代わりに多くのリストを作成します

ここで私が書いたものである:私は

?- num_of_childs(_x). 

を実行したときに、私は

gender(sagi,male). 
gender(limor,female). 
gender(yuval,male). 
gender(gilad,male). 
gender(shahaf,male). 
gender(yaara,female). 
parent(eyal,noam). 
parent(shiri,yuval2). 
parent(eyal,yuval2). 
parent(shiri,yonatan). 
parent(eyal,yonatan). 
parent(shahaf,gan). 
parent(yaara,gan). 

けど:(問題は最後functinが多くのリストを作成している)

father(_father,_child) :- parent(_father,_child), gender(_father,male). 
mother(_mother,_child) :- parent(_mother,_child), gender(_mother,female). 

couple(_woman,_man):- gender(_woman,female),gender(_man,male),parent(_man,_child),parent(_woman,_child). 

parents(_woman,_man,_child) :- father(_man,_child),mother(_woman,_child). 
count([],0). 
count([H|T],N) :- count(T,N1) , N is N1+1. 

child_to_couple(_woman,_man,_num):- couple(_woman,_man),findall(_child,parents(_woman,_man,_child),_childs),count(_childs,_num). 

num_of_childs(_list):- couple(_woman,_man),setof(childrens(_man,_woman,_num),child_to_couple(_woman,_man,_num),_list). 

データの例取得:

_x = [childrens(mordechai, miriam, 1)] ; 
_x = [childrens(salax, naima, 1)] ; 
_x = [childrens(eli, bella, 2)] ; 
_x = [childrens(eli, bella, 2)] ; 
_x = [childrens(zvi, tova, 1)] ; 
_x = [childrens(avram, yokeved, 1)] ; 
_x = [childrens(haim, irit, 3)] ; 
_x = [childrens(haim, irit, 3)] ; 
_x = [childrens(haim, irit, 3)] ; 
_x = [childrens(guy, pelit, 2)] ; 
_x = [childrens(guy, pelit, 2)] ; 
_x = [childrens(eyal, shiri, 3)] ; 
_x = [childrens(eyal, shiri, 3)] ; 
_x = [childrens(eyal, shiri, 3)] ; 
_x = [childrens(sagi, limor, 2)] ; 
_x = [childrens(sagi, limor, 2)] ; 
_x = [childrens(shahaf, yaara, 1)] ; 

の代わり:

_x = [childrens(sagi, limor, 2),childrens(sagi, limor, 2),childrens(shahaf, yaara, 1),..........etc] 
+0

なぜすべての匿名変数ですか? – lurker

答えて

3

あなたnum_of_childs/1通話setof/3couple/2ので、あなたは結果couple/2リターンの数を取得します。 child_to_couple/3couple/2と呼んでいるので、実際にはここではまったく必要ありません。

num_of_childs(L) :- findall(childrens(M,W,N),child_to_couple(W,M,N),L). 

しかし、大きな問題がcouple/2、あなたがそれを書かれている方法は、常に一度子供一人当たり成功したということです。これは、child_to_couple/2num_of_childs/1も複数回成功するように伝搬します。あなたはこの

couple(W,M):- 
gender(W,female), gender(M,male), 
(parent(M,C), parent(W,C) -> true ; false). 

に変更すると

あなたは関係なく、子供の数の、カップルごとに1つのだけの結果を得ます。私はこれを達成するためのさらに簡単な方法があるかもしれないという気持ちがありますが、私はそれを見つけることができませんでした。

?- num_of_childs(L). 
L = [childrens(eyal,shiri,2),childrens(shahaf,yaara,1)] ? ; 
no 

追加:カットを使用すると、少しシンプルになりますが、醜いものになります。

関連する問題