...

/

Creating Higher-Order Functions for Lists

Creating Higher-Order Functions for Lists

Learn how to create higher-order functions for lists.

Using functions in variables, like with any other value, can be hard to remember for newcomers. To practice, we’ll work with a subject familiar to us: lists. They’re a useful data type and are present in almost any program we need to build. We’ve seen how to work with them using recursive functions, but if we stop and look again at all that code we’ve written, we’ll see that they are a little repetitive and boring. We always have code that navigates through each item and stops when the list is empty. Now, we’ll look at building higher-order functions that hide the tedious tasks and provide an interface for what matters. Let’s start with the navigation routine.

Navigating through items of a list

A common task when working with lists is to travel through all the items and do some computation on them. The first higher-order function we’ll create allows us to navigate a list by passing a function that computes each item. Our first task is to create a variable that holds a list to test. Let’s go back to our old fantasy friend, Edwin the wizard, and store some of his enchanted items in a variable.

$iex
iex> enchanted_items = [
%{title: "Edwin's Longsword", price: 150}, 
%{title: "Healing Potion", price: 60}, 
%{title: "Edwin's Rope", price: 30}, 
%{title: "Dragon's Spear", price: 100}
]

Now people are coming to the store and want to know the items’ names. Let’s create some code that prints that information. With this routine, Edwin can prepare more magic potions while the program states the items’ names for the buyers. To do that, we need to navigate through each list element. In this lesson, we’ll create several functions for lists, create a module called MyList in a my_list.ex file, and put all the functions there. The first function is called each/2.

defmodule MyList do
  def each([], _function), do: nil
  def each([head | tail], function) do
    function.(head)
    each(tail, function)
  end 
end

The function receives two arguments: the first is the list that we’ll navigate, and the second is a function that will be called for each element of the list. The stop-condition clause is called when the list is empty; then it does nothing. The other clause is called when the list has elements. Then, we use the code function.(head) to call the function received in the argument, passing an element of the list. It runs recursively when the list has multiple elements. Let’s try it using our terminal above:

$iex
iex> enchanted_items = [
%{title: "Edwin's
...