简体   繁体   English

Prolog-如何保存递归调用的结果?

[英]Prolog - How can I save results from recursive calls?

I am still trying to understand the Prolog logic and have stumbled upon a problem. 我仍在尝试理解Prolog逻辑,并且偶然发现了一个问题。 I am trying to save values found within recursive calls, to pass on or gather. 我试图保存在递归调用中找到的值,以传递或收集。

As such: 因此:

main([]) :- !.
main([H|Tail]) :- findall(X,something(_,_,X),R),
                  getValueReturn(R,H,Lin, Lout),
                  main(Tail).


% X is the Head from main
getValueReturn([H|Tail],X,Lin, Lout) :- subset(X, H) ->
                                findall(A,something(A,_,H),L1),
                                append(Lin,L1,Lout), 
                                getValueReturn(Tail,X,Lout,L)
                                ;
                                getValueReturn(Tail,X,Lin,Lout).  

I would like to gather the results from findall in getValueReturn, combine them, and send them back to main, which can then use them. 我想从getValueReturn中的findall收集结果,将它们组合起来,然后将它们发送回main,然后可以使用它们。 How do I create and add to a list within getValueReturn? 如何在getValueReturn中创建并添加到列表? Similarly, how can I save the list in my main for all recursive calls? 同样,如何将列表保存在所有递归调用的主目录中?

EDIT: 编辑:

I edited the code above as per a comment reply, however when I run this through trace, the list deletes all elements when the empty list is found. 我根据评论答复编辑了上面的代码,但是当我通过跟踪运行此代码时,找到空列表后,列表将删除所有元素。

What am I doing wrong? 我究竟做错了什么? This is the first time I try to use the concept of building a list through recursion. 这是我第一次尝试使用通过递归构建列表的概念。

You should post complete code that can be run, with example data. 您应该发布可运行的完整代码以及示例数据。 I have not tested this. 我还没有测试。

You need to pass L around on the top-level also. 您还需要在顶级传递L Using the same variable names for different parameters in adjacent procedures does not improve readability. 在相邻过程中为不同的参数使用相同的变量名不会提高可读性。

main([E|Es],L0,L) :-
  findall(X,something(_,_,X),Rs),
  getValueReturn(Rs,E,L0,L1),
  main(Es,L1,L).
main([],L,L).

getValueReturn([R|Rs],E,L0,L) :-
  ( subset(E,R) ->
    findall(A,something(A,_,R),New),
    append(L0,New,L1), 
    getValueReturn(Rs,E,L1,L)
  ; getValueReturn(Rs,E,L0,L) ).
getValueReturn([],_,L,L).

A variable can only have one value in Prolog. 变量在Prolog中只能有一个值。 In your code, for example, Lout is the output from append/3 , an input to a recursive call of getValueReturn/4 , and then also the output on the top-level. 例如,在您的代码中, Loutappend/3的输出,是getValueReturn/4的递归调用的输入,也是顶级的输出。 This is probably not going to do what you want. 这可能不会做您想要的。

I have found the best way to do what I was trying to was to use asserta/z when a result was found, and then gather these results later on. 我找到了执行尝试的最佳方法是找到结果后使用asserta / z,然后稍后收集这些结果。

Otherwise the code became overly complicated and did not function as intended. 否则,代码将变得过于复杂,并且无法按预期运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM