循环列表可以在Erlang中定义? [英] Can Circular Lists be defined in Erlang?

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

问题描述

是否可以在erlang中定义一个循环列表?
http://en.wikipedia.org/wiki/Linked_list

is it possible to define a circular list in erlang? http://en.wikipedia.org/wiki/Linked_list

第一个问题是在erlang中一个循环列表是什么意思?
是两个元素,一个元素的自身和旁边的地址到下一个元素,存储在列表中?

first question would be what exactly a circular list mean in erlang? is it with two elements, one element its self and next to it address to the next element, stored in a list?

如果是这样我可以说是在erlang中定义循环列表的一种可能性。
但我需要澄清天气是我认为循环列表在erlang?

if so i can say there is a possibility of defining a circular list in erlang. but i need clarification weather is it what i think a circular list is in erlang?

推荐答案

没有建立列表机制来做。但是,您可以使用持有您访问的元素的元组来构建一个。

There is no built-in list mechanism to do it. However, you can build one using a tuple holding the elements you've visited or not.

基本结构是一个包含两个列表的元组: {旧,新} 。当你第一次开始一个空列表,它看起来像 {[],[]} 。当您填写列表时,请填写列表:

The basic structure is a tuple with two lists: {Old, New}. When you first start with an empty list, it looks like {[],[]}. When you fill the list, you fill it in the New list:

new() -> {[], []}.

insert(X, {Old, New}) -> {Old, [X|New]}.

peek({_Old, [H|_]}) -> X.

要在列表中移动,您所做的是首先在新的列表,并将值放在旧版本中:

To move within the list, what you do is first seek in the New list, and put the value in the old one:

next({Old, [H|New]}) -> {[H|Old], New}.

没关系,就像我们只是丢弃旧元素一样。当我们点击列表的末尾时会发生什么?我们需要修复函数(也可以看看):

That's fine and it works as if we were just discarding old elements. What happens when we hit the end of the list though? We need to fix the function (and also the peek one):

peek({Old, []}) -> hd(lists:reverse(Old));
peek({_Old, [H|_]}) -> X.

next({Old, []}) -> 
    {[], lists:reverse(Old)}}.
next({Old, [H|New]}) -> 
    {[H|Old], New}}.

如果列表中没有任何内容,它将崩溃。你也可以返回'undefined',如果你想通过特殊的套管:

If there's nothing in the list, it crashes. You could also return 'undefined' if you wanted to by special casing it:

next({[], []}) ->
    undefined;
next({Old, []}) -> 
    {[], lists:reverse(Old)}.
next({Old, [H|New]}) -> 
    {[H|Old], New}.

然后,您可以使用next,peek和delete下面)做正常的东西。我们还可以添加一个prev函数来允许向后浏览:

This then lets you use the function 'next', 'peek' and possibly 'delete' (see below) to do normal stuff. We could also add a 'prev' function to allow backwards browsing:

prev({[], []}) ->
    undefined;
prev({[], New}) -> 
    {lists:reverse(New), Old}.
prev({[H|Old], New}) -> 
    {Old, [H|New]}.

delete({Old, []}) -> {[], tl(lists:reverse(Old))};
delete({Old,[H|New]}) -> {Old, New};

这应该涵盖大部分。

这篇关于循环列表可以在Erlang中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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