O'Reilly logo

Elixir Cookbook by Paulo A Pereira

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding and subtracting lists

Lists are widely used in functional programming languages, and Elixir is no exception.

Although lists might resemble other languages' arrays, they actually behave more like single-linked lists. Operations with lists are quite common, so in this recipe, we will show you how to add two lists or subtract one list from another.

Getting ready

We will use IEx for this recipe, so start a new session by typing iex in your console.

How to do it…

To add lists, we will use the ++ operator. The steps are as follows:

  1. Create a list named list_one:
    iex(1)> list_one = [1, 3, 5]
    [1, 3, 5]
    
  2. Create a list named list_two:
    iex(2)> list_two = [2, 4, 6, 5]
    [2, 4, 6, 5]
    
  3. Add list_one to list_two:
    iex(3)> list_one ++ list_two
    [1, 3, 5, 2, 4, 6, 5] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required