Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

closest thing to arrays in Elixir

what is the closest thing to Arrays in Elixir. By arrays I mean, a container for values which I can access in constant time.

I've looked at tuple, but according to the documentation:

Tuples are not meant to be used as a “collection” type (which is also suggested by the absence of an implementation of the Enumerable protocol for tuples): they’re mostly meant to be used as a fixed-size container for multiple elements.

What I actually want to do: I want to store n processes in an array and periodically pick a random process and send it a message. I'm open to other suggestions too.

like image 705
Anurag Peshne Avatar asked Sep 23 '17 23:09

Anurag Peshne


People also ask

Does Elixir have arrays?

Arrays is a library to work with well-structured Arrays with fast random-element-access for Elixir, offering a common interface with multiple implementations with varying performance guarantees that can be switched in your configuration.

How do you find the length of a list in Elixir?

The length() function returns the length of the list that is passed as a parameter.

How do I add an element to a list in Elixir?

There is no way of appending an element to a list in Erlang either. In Elixir and Erlang we use `list ++ [elem]` to append elements.


Video Answer


3 Answers

I ended up using a combination of list and registry since I was working with processes. I got many responses on Elixir forum which I'm listing below for future reference:

  1. Tuple: stored continuous in memory, constant access time, editing results in copying whole structure. Does not implement Enumerable protocol.
  2. linked-List: O(n) access time, prefixing is cheaper than suffixing. Implements Enumerable protocol.
  3. Map: O(log n) read, write, delete time. Also implements Enumerable protocol.
  4. :array: array module from Erlang.
  5. registry: (applicable only if storing processes) A local, decentralized and scalable key-value process storage.

Also, note 2 and 3 (List and Map) are persistent data structures.

like image 169
Anurag Peshne Avatar answered Oct 17 '22 01:10

Anurag Peshne


There are also two Elixir packages Arrays and Tensor that provide similar functionalities.

like image 2
xji Avatar answered Oct 17 '22 03:10

xji


Elixir has an array module via erlang: http://erlang.org/doc/man/array.html

like image 1
Mike Buhot Avatar answered Oct 17 '22 02:10

Mike Buhot