May 2018
Intermediate to advanced
412 pages
9h 3m
English
A single function definition lets you define different implementations, depending on the type and contents of the arguments passed. (You cannot select based on the number of arguments—each clause in the function definition must have the same number of parameters.)
At its simplest, we can use pattern matching to select which clause to run. In the example that follows, we know the tuple returned by File.open has :ok as its first element if the file was opened, so we write a function that displays either the first line of a successfully opened file or a simple error message if the file could not be opened.
| 1: | iex> handle_open = fn |
| 2: | ...> {:ok, file} -> "Read data: #{IO.read(file, :line)}" |
| 3: ... |
Read now
Unlock full access