序言,复制列表 [英] prolog, copying lists

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

问题描述

我正在尝试绕开一些基本的序言,但在此过程中有些挣扎.具体来说-我试图遍历项目列表并将其逐项复制到新列表中.我可以使它反转,但是我发现在不反转的情况下这样做比较棘手.

I am attempting to get my arms around some basic prolog but struggling a bit in the process. In specific - I am trying to get through a list of items and copy it, item by item into a new list. I can get it to reverse, but I am finding it trickier doing it without reversing.

我一直在尝试以下方法-

Ive been trying the following -

copy(L,R) :- accCp(L,R).

accCp([],R).
accCp([H|T],R) :- accCp(T,H).

当我对此进行跟踪时-我可以看到复制的各个项目,但是它们丢失了",并且没有形成一个不断增长的列表(正如我希望的那样,在R处).我怎么能做到这一点?

When i run a trace on this - i can see the individual items being copied across, but they get 'lost', and dont form a growing list (at R, as i was hoping). How could i achivie this?

非常感谢

推荐答案

您的基本情况需要在原始列表为空时将副本列表设置为空.然后,递归案例需要从列表L中获取H并将其添加到列表R的头部:

Your base case needs to set the copy list to empty when the original list is empty. Then, the recursive case needs to take H from list L and add it to the head of list R:

copy(L,R) :- accCp(L,R).
accCp([],[]).
accCp([H|T1],[H|T2]) :- accCp(T1,T2).

当您调用copy时,它会一直工作到基本情况,在该情况下会将R设置为空列表.然后,在备份时,它将继续将已知列表[H|T1]的头部H附加到变量列表[H|T2]的开头.它会一直执行到达到原始大小写为止,此时R包含L的完整副本.

When you call copy, it works its way down to the base case, where it sets R to an empty list. Then, as it works back up, it keeps appending the head H of known list [H|T1] to the beginning of variable list [H|T2]. It does that until the original case is reached, at which point R contains a full copy of L.

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

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