反转Prolog中的列表 [英] Reversing a List in 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
For further information please read: http://www.learnprolognow.org/lpnpage.php?pagetype=html&pageid=lpn-htmlse25
这篇关于反转Prolog中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!