在 Prolog 中反转列表 [英] Reversing a List in Prolog

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

问题描述

我已经完成了我的编程课的家庭作业.我应该创建一个反转列表的 Prolog 程序.但是,我很难理解它为什么会起作用.

I have finished a homework assignment for my programming class. I was supposed to create a Prolog program that reverses a list. I, however, am having trouble understanding why exactly it works.

%1. reverse a list
%[a,b,c]->[c,b,a]

%reverse(list, rev_List).
reverse([],[]).  %reverse of empty is empty - base case
reverse([H|T], RevList):-
    reverse(T, RevT), conc(RevT, [H], RevList).  %concatenation

在这种情况下,RevT 到底是什么?我知道它应该代表 T 的反转或给定列表的其余部分,但我看不出它如何具有任何价值,因为我没有将它分配给任何东西.它是否与 RevList 具有相同的目的,但对于每个递归调用?

What exactly is RevT in this case? I know it is supposed to represent the reverse of T or the rest of the given list, but I don't see how it could have any value as I haven't assigned it to anything. Does it just serve the same purpose as RevList but for each recursive call?

另外,为什么我必须在 conc() 函数调用中使用 [H] 而不是仅使用 H?H 不是指列表的头部(例如:[H])吗?或者它只是指列表头部的项目(只是 H)?

Also, why do I have to use [H] instead of just H in my conc() function call? Doesn't H refer to the head of the list (ex: [H])? Or does it just refer to the item at the head of the list (just H)?

请帮我解决这个问题.我很难理解这种编程背后的逻辑.

Please help clear this up for me. I am struggling to understand the logic behind this type of programming.

推荐答案

您的解决方案说明:如果我们反转空列表,我们将获得空列表.如果我们反转列表 [H|T] ,我们最终得到通过反转 T 并与 [H] 连接获得的列表.要查看递归子句是否正确,请考虑列表 [a,b,c,d] .如果我们反转这个列表的尾部,我们会得到 [d,c,b] .将其与 [a] 连接会产生 [d,c,b,a] ,这是 [a,b,c,d] 的反面

Your solution explained: If we reverse the empty list, we obtain the empty list. If we reverse the list [H|T] , we end up with the list obtained by reversing T and concatenating with [H] . To see that the recursive clause is correct, consider the list [a,b,c,d] . If we reverse the tail of this list we obtain [d,c,b] . Concatenating this with [a] yields [d,c,b,a] , which is the reverse of [a,b,c,d]

另一种反向解决方案:

 reverse([],Z,Z).

 reverse([H|T],Z,Acc) :- reverse(T,Z,[H|Acc]).

呼叫:

?- reverse([a,b,c],X,[]).

更多信息请阅读:http://www.learnprolognow.org/lpnpage.php?pagetype=html&pageid=lpn-htmlse25

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

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