PROLOG 中的递归? [英] Recursion in PROLOG?

查看:37
本文介绍了PROLOG 中的递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下 Prolog 事实:

Given the following Prolog facts:

f(a, [b]).
f(b, [c]).
f(c, [d]).
f(d, [e]).
f(e, []).

我需要创建一个查询 xyz(a,Y) 以便我得到 Y = [e,d,c,b],因为 a 取决于 b,这取决于 c 等.我当前的查询是:

I need to create a query xyz(a,Y) so that I get Y = [e,d,c,b], since a depends on b, which depends on c, etc. My current query is:

xyz(X,Y):-
  f(X,P),
  member(Y,[P]).

然而,这个对 xyz(a,Y) 的查询只给了我 Y = [b],而不是 b 的依赖等.

However, this query for xyz(a,Y) only gives me Y = [b], and not b's dependents, etc.

我想也许我可以将这两行添加到上面查询的末尾,但这并不像我希望的那样工作.由于之前的免费查询成功检索了 a 的依赖 b,我希望接下来的两行可能对 b 和 on 做同样的事情.但是,我认为这可能不是处理它的好方法.也许递归是一个更好的主意.

I figured that perhaps I can add these two lines to the end of the query above, but that doesn't work as I would like it to. Since the previous free query successfully retrieves a's dependent b, I was hoping these next two lines could perhaps do the same for b and on. But, I don't think this is a good way to approach it maybe. Maybe recursion is a better idea.

f(P,S),
member(Y,[P]).

我很确定我应该在最后添加一个递归,但我不确定如何处理.有人可以帮我吗?

I'm pretty sure that I should add a recursion in the end, but I am not sure how to approach. Can someone help me please?

(3/4)

我能够使用下面的@CapelliC 方法成功解决单元素列表的问题.但是,我想扩展这个问题,使其适用于多元素列表,其中 Prolog 事实现在看起来像:

I was able to successfully solve the issue of single-element lists with @CapelliC approach below. However, I would like to extend this problem so that it works for multiple-element lists, where the Prolog facts now look like:

f(a, [b, d]).
f(b, [c]).
f(c, []).
f(d, [e]).
f(e, [f]).
f(f, [g).
f(g, []).

在这种情况下,xyz(a,X) 的查询应该给我:X = [b,c,d,e,f,g],元素顺序不一定重要,我可以在之后排序.

In this case, query of xyz(a,X) should give me: X = [b,c,d,e,f,g], the element-order doesn't necessarily matter, I can sort that after.

这是以前适用于单列表的代码:

This was the previous code that works for single-lists:

xyz(Z, [X|Y]):-
    f(Z,[X]),
    !,
    xyz(X,Y).
    xyz(_,[]).

根据@lurker,我需要合并成员函数,但我遇到了问题.这是我目前的方法,但它不起作用,只是给了我一个空列表作为所有内容的输出:

According to @lurker I need to incorporate the member function, but I am having trouble with it. This is my current approach, but it doesn't work and just gives me an empty list as output for everything:

xyz(Z, [X|Y]):-
    f(Z,X),
    member(Y,X), // I'm not sure if this should be a 'Y'
    !,
    xyz(X,Y).
    xyz(_,[]).

有什么想法吗?

推荐答案

此代码段以相反的顺序获取列表,写下您的请求...

this snippet get the list in reverse order, wrt your request...

xyz(K, [D|Ds]) :- f(K, [D]), !, xyz(D, Ds).
xyz(_, []).

edit 扩展到多个依赖元素(但没有循环!)可以像

edit extending to multiple dependency elements (but without loops !) could be done like

xyz(K, Ds) :- f(K, DKs) -> findall([T|P], (member(T, DKs), xyz(T, P)), L), flatten(L, F), sort(F, Ds) ; Ds = [].

这篇关于PROLOG 中的递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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