如何在prolog中计算prolog中父母的孩子数量(不使用列表)?
我有以下问题。我有一定数量的事实,例如: 父母(简,迪克)。 父母(迈克尔,迪克)。 我想要一个谓词,例如: 孩子数量(迈克尔,X) 所以如果我这样称呼它,它会显示 X=1。
我在网上搜索过,每个人都将孩子放入列表中,有没有办法不使用列表?
I have the following problem. I have a certain number of facts such as:
parent(jane,dick).
parent(michael,dick).
And I want to have a predicate such as:
numberofchildren(michael,X)
so that if I call it like that it shows X=1.
I've searched the web and everyone puts the children into lists, is there a way not to use lists?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
计算解决方案的数量需要一些额外的逻辑工具(它本质上是非单调的)。这是一个可能的解决方案:
Counting number of solutions requires some extra logical tool (it's inherently non monotonic). Here a possible solution:
我只能看到两种方法来解决这个问题。
第一个似乎更容易,是将所有解决方案放在一个列表中并对其进行计数。我不确定您为什么不喜欢这个选项。您是否担心效率或其他问题?还是只是一个任务?
问题是,如果不使用像
setof/3
这样的元逻辑谓词,您将不得不允许 Prolog 以通常的方式绑定值。如果你让 Prolog 这样做,循环的唯一方法就是失败,就像这样:但这不会起作用;首先,您将得到
参数未充分实例化
。然后你要解决这个问题并得到这样的结果:原因是,如果 Prolog 要逐一检查事实,则需要回溯,并且每次回溯时,它都会解除自上次选择以来绑定的任何内容观点。我知道跨过这个障碍传递数据的唯一方法是使用动态存储:
我还没有测试过这个,因为我认为它相当恶心,但如果不这样做,它可能会起作用。 :)
无论如何,如果可能的话,我强烈建议您选择列表选项。
I can only see two ways to solve this.
The first, which seems easier, is to get all the solutions in a list and count it. I'm not sure why you dislike this option. Are you worried about efficiency or something? Or just an assignment?
The problem is that without using a meta-logical predicate like
setof/3
you're going to have to allow Prolog to bind the values the usual way. The only way to loop if you're letting Prolog do that is with failure, as in something like this:This isn't going to work though; first you're going to get
arguments not sufficiently instantiated
. Then you're going to fix that and get something like this:The reason is that you need Prolog to backtrack if it's going to go through the facts one by one, and each time it backtracks, it unbinds whatever it bound since the last choice point. The only way I know of to pass data across this barrier is with the dynamic store:
I haven't tested this, because I think it's fairly disgusting, but it could probably be made to work if it doesn't. :)
Anyway, I strongly recommend you take the list option if possible.