Prolog/介绍/答案
外观
我们将使用以下数据库来表示此家族树的一部分。
man(sirius_black). man(regulus_black). man(orion_black). man(cygnus_black). man(pollux_black). woman(bellatrix_black). woman(andromeda_black). woman(narcissa_black). woman(walburga_black). woman(druella_roisier). woman(irma_crabbe). parent(orion_black, sirius_black). parent(walburga_black, sirius_black). parent(orion_black, regulus_black). parent(walburga_black, regulus_black). parent(cygnus_black, bellatrix_black). parent(druella_roisier, bellatrix_black). parent(cygnus_black, andromeda_black). parent(druella_roisier, andromeda_black). parent(cygnus_black, narcissa_black). parent(druella_roisier, narcissa_black). parent(pollux_black, walburga_black). parent(irma_crabbe, walburga_black). parent(pollux_black, cygnus_black). parent(irma_crabbe, cygnus_black).
1. 列出数据库中的女性
?- woman(Woman). Woman = bellatrix_black ; Woman = andromeda_black ; Woman = narcissa_black ; Woman = walburga_black ; Woman = druella_rosier ; Woman = irma_crabbe.
2. 列出数据库中的孩子
?- parent(_, Child). Child = sirius_black ; Child = sirius_black ; Child = regulus_black ; ...
3. 列出所有父亲和儿子的组合。
?- parent(Father, Son), man(Father), man(Son). Father = orion_black, Son = sirius_black ; Father = orion_black, Son = regulus_black ; Father = pollux_black, Son = cygnus_black ; fail.
4. 哪些女性在数据库中既有父亲又有儿子?
?- woman(Woman), parent(Father, Woman), parent(Woman, Son), man(Father), man(Son). Woman = walburga_black, Father = pollux_black, Son = sirius_black; Woman = walburga_black, Father = pollux_black, Son = regulus_black ; fail.
5. (额外问题) 你能想出一个方法来显示数据库中没有列出父亲的女性吗?你能描述一下你需要编写这样的查询需要做什么吗?
你需要使用否定。
要放入 db 中的规则
hasFather(Somebody):- parent(Father,Somebody), man(Father). womenWithNoFather(Woman) :- woman(Woman), \+ hasFather(Woman).
查询
?- womenWithNoFather(Woman). Woman = druella_roisier ; Woman = irma_crabbe ; fail.