Prolog:获取谓词解决方案并将其断言为事实 [英] Prolog: Getting predicate solutions and asserting them as facts

查看:49
本文介绍了Prolog:获取谓词解决方案并将其断言为事实的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具体问题,但我会尝试提出一个一般性问题,以便其他人也可以从中受益...

我有一个返回许多解决方案的谓词,即

X=5;X=2;X=7

并且我想要一个谓词来获取这些解决方案中的每一个并将它们断言为 Prolog 事实,所以在这种情况下我最终得到三个事实,例如

事实(5)事实(2)事实(7)

所以调用 fact(5) 是正确的,但调用 fact(8) 是错误的,因为我们从未断言它,因为它不是解决方案.>

但我不想有一个谓词,您必须不断寻求解决方案来断言每个事实.我想调用一个谓词,让它通过后台的所有解决方案,断言它们,就是这样.

解决它的一种方法是使用 findall 将所有解决方案放入一个列表中,然后只需遍历列表,断言列表中的每个元素.但是,我认为这不是很优雅.必须有一种更好的方法来做到这一点,而无需摆弄列表.

解决方案

使用故障驱动循环强制回溯所有解决方案:

?- 计算(X),假.

您可以使用 ignore/1 忽略此查询的声明性错误真值:

?- 忽略((计算(X),假)).

I've got a specific problem but I'll just try and come up with a general question so other people might benefit from it too...

I've got a predicate that returns many solutions i.e.

X=5; X=2; X=7

and I want a predicate that gets each of these solutions and asserts them as Prolog facts then so I end up with three facts in this case e.g.

fact(5) fact(2) fact(7)

so calling fact(5) would be true but calling fact(8) would be false because we never asserted it because it wasn't a solution.

But I don't want to have a predicate where you have to keep asking for solutions to assert each single fact. I want to call a predicate and have it go through all the solutions in the background, assert them and that's it.

One way of solving it is using findall to put all the solutions into a list and then just go through the list asserting each element of the list. However, I don't think this is very elegant. There must be a nicer way of doing it without fiddling around with lists.

解决方案

Use a failure-driven loop to force backtracking over all solutions:

?- computation(X), false.

You can ignore this query's declaratively false truth value with ignore/1:

?- ignore((computation(X),false)).

这篇关于Prolog:获取谓词解决方案并将其断言为事实的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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