如何停止序言中规则的重复 [英] How to stop repetitions in rules in prolog

查看:50
本文介绍了如何停止序言中规则的重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的序言规则中

marriedcouple(X,Y) :-
    parent( (X,Z), bornin(_) ),
    parent( (Y,Z), bornin(_) ),
    female(X),
    male(Y)
    ;
    male(X),
    female(Y),
    different(X,Y).

当父母有两个孩子时,这对夫妇会出现两次.我们如何防止这种情况发生?

when a parent has two kids, the couple shows twice. How can we prevent this ?

推荐答案

鉴于你有 female/1 &male/1 谓词 谓词变得非常简单.

Given that you've got female/1 & male/1 predicates the predicate becomes quite simple.

marriedcouple(X,Y) :-
    parent( (X,Z), bornin(_) ),
    parent( (Y,Z), bornin(_) ),
    female(X),
    male(Y).

但是,如果您想查看 X 和 Y 是否不同,请使用 (\==)/2 运算符表示不相同"或 (\=)/2 表示不可统一".

However, if you want to see if X and Y are not the same use the (\==)/2 operator for "not identical" or (\=)/2 for "not unifiable".

Pradeep,根据您在下面的评论,这里有一个更完整的解决方案.

Pradeep, based on your comment below, here is a more complete solution.

为了防止相同的答案出现两次,有多种选择.我们可以建立一个解决方案列表,并且只添加一个新发现的解决方案,如果它不在列表中.或者使用使用 assert/1 谓词合并状态的方法.

In order to prevent the same answer coming back twice there's a number of choices. We can build a list of solutions and only add a newly found solution if it isn't already in the list. Or use an approach that incorporates state using the assert/1 predicate.

我选择了后者.

?- solve.

solve :-
    marriedcouple(Dad, Mum),
    not( found( marriedcouple(Dad, Mum) ) ),
    assert( found( marriedcouple(Dad, Mum) ) ),
    write( [Dad, Mum] ),
    nl,
    fail.

marriedcouple(Dad, Mum) :-
    parent(Dad, Child),
    parent(Mum, Child),
    male(Dad),
    female(Mum).

male(aaron).
male(adam).

female(betty).
female(eve).

parent(aaron, callum).
parent(aaron, david).
parent(adam, abel).
parent(adam, cain).
parent(betty, callum).
parent(betty, david).
parent(eve, abel).
parent(eve, cain).

当我运行它时,我得到以下内容:

When I run this I get the following:

[aaron,betty];
[adam,eve];
No.

小心使用 assert/1 谓词,因为您可能会在程序中引入不需要的副作用.您可能还需要进行适当的 retract/1 调用.

Be careful using assert/1 predicates as you may introduce unwanted side-effects into your programs. You may need to do appropriate retract/1 calls too.

这篇关于如何停止序言中规则的重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆