反转列表 [英] Reversing a list

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

问题描述

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

xyz(X,Y): -
fun(X,Z) - > findall([A | B],(member(A,Z),xyz(A,B)),L),
flatten(L,F),sort(F,Y); Y = []。

查询 xyz(a,X)。给我 X = [b,c,d,e,f,g]。
但是,我希望它给我 X = [g,f,e,d,c,b]



我尝试了不同的尝试来反转列表,我没有任何运气。



我曾尝试在此之后添加额外的谓词,但它也不起作用:



pre $
$ x $ z $($,$) \ = 0。

感谢CapelliC提供上述实现方法,在我的另一篇文章中发现。
PROLOG中的递归?

解决方案

你可以避免一些困难的编程,并通过重新定义你的问题让你的程序更容易阅读。假设 f / 2 描述了一个有向图,从第一个参数到第二个参数中的每个元素的边都是这样:

  a --->> b 
a ---> d
b ---> c
%etc

然后,您的问题是,图中的哪些节点可以从一个给定的节点?您可以在 library(ugraphs)帮助下定义解决方案,



要从 f / 2

  edge(从 - 到): -  
f(From,L),
成员L)。

您现在可以收集边界,绘制图形,并查找哪些节点可从起始节点到达:
$ b

  foo(X,L): -  
findall(E,edge(E),Edges),
vertices_edges_to_ugraph([],Edges,G),
reachable(X,G,All),
once(select(X,All,R)),%从
反转(R,L)。

根据定义,节点始终可以从本身到达,因此您需要从列表中选取它。

 ? -  foo(a,X)。 
X = [g,f,e,d,c,b]。

? - foo(e,X)。
X = [g,f]。

? - foo(g,X)。
X = []。

我不完全明白为什么元素的顺序很重要。这感觉有点像代码味道。


I need help reversing a list.

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

xyz(X, Y):- 
    fun(X, Z) -> findall([A|B], (member(A, Z), xyz(A, B)), L),
    flatten(L, F), sort(F, Y); Y = [].

The query xyz(a,X). gives me X = [b,c,d,e,f,g]. However, I would like it to give me X = [g,f,e,d,c,b].

I have tried different attempts at reversing the list, but I am not having any luck.

I have tried adding an additional predicate right after this, but it didn't work either:

xyz2(X,Y):-
    xyz(X,Y),
    reverse(Y,Z),
    Z\=0.

Credit goes to CapelliC for the approach to the implementation above found at my other post here. Recursion in PROLOG?

解决方案

You can avoid some difficult programming, and make your program easier to read by re-defining your problem. Say the f/2 describes a directed graph, with edges from the first argument to each of the elements in the second argument, so:

a ---> b
a ---> d
b ---> c
% etc

Then, your question is, which nodes in the graph are reachable from a given node? You can define the solution with the help of library(ugraphs).

To make all edges from an f/2:

edge(From-To) :-
    f(From, L),
    member(To, L).

You can now collect the edges, make a graph, and find which nodes are reachable from a starting node:

foo(X, L) :-
    findall(E, edge(E), Edges),
    vertices_edges_to_ugraph([], Edges, G),
    reachable(X, G, All),
    once(select(X, All, R)), % remove the node you start from
    reverse(R, L).

Per definition, a node is always reachable from itself, so you need to pick it out of the list of reachable nodes.

?- foo(a, X).
X = [g, f, e, d, c, b].

?- foo(e, X).
X = [g, f].

?- foo(g, X).
X = [].

I don't exactly understand why the order of the elements is significant. This feels a bit like a code smell.

这篇关于反转列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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