在 Prolog 中获取解决方案列表 [英] Getting list of solutions in Prolog

查看:48
本文介绍了在 Prolog 中获取解决方案列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习序言,我正在阅读一本名为《人工智能编程序言》的书.作为练习,我想学习如何扩展本书中的一个示例.有人可以帮忙吗?

I am learning prolog and I am reading a book called Programming Prolog for Artificial Intelligence. As practice I want to learn how to extend one of the examples in this book. Can someone please help?

假设你有这些事实:

parent(pam, bob). %pam is a parent of bob
parent(george, bob). %george is a parent of bob

我将如何编写一个 prolog 谓词来为我提供 bob 父母的列表?例如:

How would I write a prolog predicate that would give me a list of bobs parents? For example:

list_parents(bob, L).

L = [pam, george] ;
L = [george, pam] ;
true.

推荐答案

findall/3 这样的全解谓词可能会解决问题:

An all-solutions predicate like findall/3 might do the trick:

list_parents(P, L) :-
    findall(Parent, parent(Parent, P), L).

简单地说,findall/3 在'backtrack-able'目标parent(Parent, P)中找到Parent的所有绑定,并将Parent的所有绑定放入列表L.请注意,这不会删除重复项,但您可以在返回它以创建集合之前对 L 执行 sort/2 .执行这个:

Simply put, findall/3 finds all bindings for Parent in the 'backtrack-able' goal parent(Parent, P), and puts all bindings of Parent into the list L. Note that this won't remove duplicates, but you can do a sort/2 to L before returning it to create a set. Executing this:

?- list_parents(bob, L).
L = [pam, george].

如果您的 PROLOG 实现中没有 findall/3,您可以像这样手动执行:

If you don't have findall/3 in your PROLOG implementation, you could do it manually like this:

list_parents(P, L) :-
    list_parents(P, [], L).

list_parents(P, Acc, L) :-
    parent(Parent, P),
    \+ member(Parent, Acc), !,
    list_parents(P, [Parent|Acc], L). 
list_parents(_, L, L).

此版本将对 list_parents/2 的调用发送到累加器版本 list_parents/3.后者也尝试收集 Parent 绑定,只要我们之前没有见过它们(因此 \+ member 检查),并返回没有新 <可以找到累积到 Acc 列表中的 code>Parent 绑定.执行这个给我们与第一个选项相同的结果:

This version sends calls to list_parents/2 off to an accumulator-version, list_parents/3. The latter tries to collect Parent bindings also, as long as we haven't seen them before (hence the \+ member check), and returns the list where no new Parent bindings accumulated into the Acc list can be found. Executing this gives us the same result as the first option:

?- list_parents(bob, L).
L = [pam, george].

这篇关于在 Prolog 中获取解决方案列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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