如何使用append/3在prolog中递归构建列表?

编程入门 行业动态 更新时间:2024-10-21 20:38:27
本文介绍了如何使用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第三名的值作为一个元组,其中a与fact1匹配.抱歉,我很难解释.

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.

推荐答案

您正确地使用 findall/3 ,应该坚持下去.您的问题是您走了正确的道路.别担心,爱因斯坦在广义相对论中也是如此,他后来意识到自己的错误并回到了正确的道路上.

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中递归构建列表?

本文发布于:2023-11-30 03:18:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648547.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   如何使用   列表   prolog   append

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!