Book Image

Elixir Cookbook

By : Paulo Pereira
Book Image

Elixir Cookbook

By: Paulo Pereira

Overview of this book

Table of Contents (16 chapters)
Elixir Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating and manipulating keyword lists


Tuples are often used to represent associative data structures. In Elixir, a list of two element tuples whose first element is an atom is called a keyword list.

Keyword lists have some particular features:

  • They maintain the order of the elements as defined when creating and adding elements

  • They allow repeated keys

Getting ready

Start a new IEx session by entering iex in your command line.

How to do it…

We will follow these steps to create and manipulate keyword lists:

  1. Create a list with three tuples:

    iex(1)> t1 = {:jane, 23}
    iex(2)> t2 = {:jill, 44}
    iex(3)> t3 = {:joe, 32}
    iex(4)> kw_list = [t1, t2, t3]
    [jane: 23, jill: 44, joe: 32]
    
  2. Add a new entry at the end of the list:

    iex(5)> kw_list = kw_list ++ [anthony: 22]
    [jane: 23, jill: 44, joe: 32, anthony: 22]
    
  3. Add a new entry at the beginning of the list:

    iex(6)> kw_list = [zoe: 28] ++ kw_list
    [zoe: 28, jane: 23, jill: 44, joe: 32, anthony: 22]
    
  4. Add an already existing key to the list:

    iex(7...