2

我有一个使用 prolog 创建的函数,由于某种原因,它总是为每个元素创建多个列表而不是一个列表,有人可以帮我吗?

这是我写的:(问题是最后一个函数创建了许多列表)

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).

数据示例:

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).

但是当我跑步时

 ?- num_of_childs(_x).

我得到:

_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]
4

1 回答 1

3

您在 之前的num_of_childs/1调用,因此您获得了返回结果的数量。由于还调用了您实际上根本不需要它。couple/2setof/3couple/2child_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/2并且num_of_childs/1也会成功多次。

如果你改成这个

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

无论孩子有多少,每对夫妇只能得到一个结果。我觉得可能有一种更简单的方法可以实现这一点,但我找不到它。

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

另外:使用剪切会稍微简单但也更丑陋。

于 2017-12-28T17:38:45.030 回答