The syntax in Elixir is a bit different than in some other common languages. It gets a lot more readable if you move the anonymous functions into separate functions.
Anonymous functions get called with a dot:
# define an anonymous function
f = fn x, y -> x + y end
# the dot is required
f.(3, 4)
#=> 7
The &1
part is explained here. It’s just capturing the first argument, which is the sum of black + white
.
You can make it more readable by moving the anonymous functions into the private section. Then the piped section reads more like English.
defmodule Game do
@doc """A more readable example."""
def total_pieces_on(board) do
board
|> count_pieces_by_color()
|> sum_all_pieces()
|> format_sum()
end
# private functions
defp count_pieces_by_color(_board), do: { 10, 11 } # skipping the computing of pieces
defp sum_all_pieces({ black, white }), do: black + white
defp format_sum(total_pieces), do: "Total pieces: #{total_pieces}"
end
Game.total_pieces_on("In a real program, this could be game board data.")
#=> "Total pieces: 21"
His Elixir course is pretty good.
Edit: fixed mistakes in the code example.