I'm new to Erlang so I am working on an example program and struggling to decide whether I should use an array or a list. Both are easy to create and handle but I didn't get:

  • How you append an item to an array without knowing an index of where it should be appended. Is array:set(array:size(A),"a",A) the way to go?
  • How to find out if a certain element is a member of the array, just as the lists:member() function does. Do I have to iterate through the entire array and check each element for this?

And last, which one is better in terms of performance?

  • Rule of thumb: Use lists unless it is obvious you shouldn't. – zxq9 Feb 23 '15 at 15:25
up vote 2 down vote accepted

Lists are a data type that is native to the Erlang VM. Arrays are implemented as a structure of nested tuples.

Lists can be used in pattern matching. Arrays shouldn't be.

As @zxq9 mentioned, lists should be used unless it's obvious that you shouldn't. The only time I think you should use an array is when a lot of random updates are performed on the collection. Otherwise just use a list.

  • As you mentioned, appending to an array can be done with array:set(array:size(A),"a",A). Prepending to a list can be done with ["a"|A]. Of course if you wanted to append to the list you could run lists:reverse followed by ["a"|A] followed by another call to lists:reverse.
  • To check if an item exists in an array, you could convert the array to a list (array:sparse_to_list(A)). Then call lists:member/2 on the resulting list.

More information on the array implementation available here: https://stackoverflow.com/a/16464349/1245380

If you think that you may need a function like lists:member/2, use a list :o)

Array brings value when it makes sense to access any element by its index, avoiding list exploration or boring tuple matches like {_,_,_,_,_,_,N,_,_,_,_} = Tuple, which is nicely replaced by N = array:get(6,Array). (or element(7,Tuple), but with tuples you don't have map, sparse_pap, foldl ...).

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.