如何使用append/3在prolog中递归构建列表? [英] How to use append/3 to recursively build a list in prolog?

查看:215
本文介绍了如何使用append/3在prolog中递归构建列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要了解一些事实.该部分似乎正在工作.

I need to get some values of facts. That part seems to be working.

fact1(A, _, Val1, _, _),
fact2(_, B, Val2, _, _),
A = B,

但是,一旦我尝试使用append/3谓词将这些值[(Val1,Val2)]附加到List(OutList)上,我只会得到一个可能的解决方案,而不是所有的列表.

But as soon as I try to append these values [(Val1,Val2)] to the List(OutList) by using the append/3 predicate, I only get one possible solution back instead of a list with all of them.

像这样添加:append(OutList, [(Val1,Val2)], OutList)也不起作用.我觉得我在这里缺少一些基本的东西.

Appending like this: append(OutList, [(Val1,Val2)], OutList) doesn't work either. I feel like I am missing something fundamental here.

到目前为止,这是我的谓词.

This is what my predicate looks like so far.

buildList(OutList):-
    fact1(A, _, Val1, _, _),
    fact2(_, B, Val2, _, _),
    A = B,
    append([], [(Val1,Val2)], OutList).

有人可以指出我的一些错误吗? 我知道这个问题可能很容易找到,但是我只是从Prolog/函数式编程开始.

Can someone point me to some mistakes I have made. I know the problem is probably pretty easy to find but I am just starting out with Prolog/functional programming.

如果我有fact1(a,b,c,d,e).fact2(f,a,g,h,i),那么我希望我的谓词给我列出所有fact2第三名和fact1第三名的值作为一个元组,其中afact1匹配.抱歉,我很难解释.

If I had fact1(a,b,c,d,e). and fact2(f,a,g,h,i), then I'd want my predicate to give me a list of all fact2 3rd place value and fact1 third place values as a tuple, where the a matches up with fact1. I have kind of a hard time explaining it, sorry.

推荐答案

您正确地使用

You were right to look at using findall/3 and should have stuck with it. Your problem is that you walked away from the right path. Don't worry, Einstein did the same with General Relativity, he latter realized his mistake and went back to the correct path.

第一部分是查找单个项目,第二部分是将它们收集到列表中.

The first part is to find the individual items, the second part is to collect them into a list.

鉴于以下事实

fact1(1, _, a, _, _).
fact1(2, _, c, _, _).
fact1(3, _, d, _, _).
fact1(4, _, f, _, _).

fact2(_, 1, b, _, _).
fact2(_, 2, c, _, _).
fact2(_, 4, e, _, _).

查找单个项目:

find_item((Val1,Val2)):-
    fact1(A, _, Val1, _, _),
    fact2(_, A, Val2, _, _).

然后将它们收集到列表中:

Then collect them into a list:

findall(Item,find_item(Item),Items).

现在为了使其更易于使用,将其放在谓词中:

Now to make it easier to use put it in a predicate:

test(Items) :-
    findall(Item,find_item(Item),Items).

示例运行:

?- test(Items).
Items = [(a, b),  (c, c),  (f, e)].


有关后续问题,请参见后续问题.

这篇关于如何使用append/3在prolog中递归构建列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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