is it possible to define a circular list in erlang? http://en.wikipedia.org/wiki/Linked_list
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?
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?
Why yes you can ;)
And here is some crappy code to prove it
Seeing erlang, and the erlang virtual machine, only supports immutable data it is impossible to build a circular list. If you were to build one yourself in some "illegal" way then it is not certain that the memory management could handle it properly.
As pointed out above, you would have to implement them yourself. But as you can associate data to other data in various ways in erlang there is nothing stopping you from doing so. Essentially you need just one thingie representing the current index and another one representing the pointer to the next index. One funny way would be starting a process for each element in the list pointing to the next(or previous) process(element) by its PID. One (or many) special purpose process(es) could be crawling those other "list"-processes. Less crazy aproaches might make use of ets or mnesia.
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 theNew
list:To move within the list, what you do is first seek in the
New
list, and put the value in the old one: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):
If there's nothing in the list, it crashes. You could also return 'undefined' if you wanted to by special casing it:
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:
And that should cover most of it.
There are no circular lists in Erlang supported by the virtual machine. You have to build them yourself if you want one.