Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Elm collections: How they work, and when to use...

Elm collections: How they work, and when to use them.

Most applications, in any language, requires the use of collections. Elm has several collection types built-in: Lists, Arrays, Sets and Dicts. When is it better to use a List instead of an Array, and when do you use Sets? In this talk, Robin explains how the different collections are implemented under the hood, with the hope that this knowledge will make it painfully obvious when to use the different collection types.

Avatar for Robin Heggelund Hansen

Robin Heggelund Hansen

June 09, 2017

Other Decks in Programming

Transcript

  1. Who am i? • Robin Heggelund Hansen • Noteworthy projects:

    • elm-community/dict-extra • Skinney/elm-array-exploration
  2. Purpose of this talk • Learn how the four core

    collection types (Lists, Arrays, Dicts and Sets) are implemented. • Because it’s fun! • It makes it clear which collection to use, in any given use case.
  3. Warning The company, characters, and implementations portrayed in this talk

    are fictitious. No identification with actual persons (living or deceased), companies and implementations is intended or should be inferred.
  4. List Summary • Ideal when operating at the head of

    the list. • Ideal for iterating from left to right. • Ideal when the most important thing is to add elements. • Everything else is sub-optimal.
  5. Dict type Dict comparable v
 = Empty
 | Node 


    comparable
 v
 (Dict comparable v)
 (Dict comparable v)
  6. Dict summary • Quick access by key. • No duplicate

    keys. • Sorted order. • Requires comparable keys.
  7. Array 143 00 111 000 000 000 000 000 000

    000 010 001 7 1 2 0 0 0 0 0 0 0 0
  8. Array summary • Fast get/set at any index. • Fast

    when adding to the end. • Fast map, filter, foldl, foldr.
  9. Summary • Use List when operating at the head, or

    when iterating through all elements from left to right. • Use Array when you need fast random access, operating at the tail, or when you require iteration from right to left. • Use Dict when you need to access elements by key. • Use Sets when you need to operate with unique values (can also use dictionary).
  10. Summary • Remember. Elm tries to help you by not

    exposing non-optimal API (like get/set for Lists). • Try to avoid converting between collection types. Compromise on the best collection for your use case.