February 2018
Beginner
200 pages
4h 37m
English
The first strategy for handling unexpected events is to control the flow like we covered in Chapter 3, Using Pattern Matching to Control the Program Flow. You can use conditional structures, like case, if, or function clauses, to handle impure function results. They are flexible and good for handling simple cases, but not so much for complex ones. Let’s see how they do the job well:
| | defmodule Shop do |
| | def checkout(price) do |
| | case ask_number("Quantity?") do |
| | :error -> IO.puts("It's not a number") |
| | {quantity, _} -> quantity * price |
| | end |
| | end |
| | |
| | def ask_number(message) do |
| | message <> "\n" |
| | |> IO.gets |
| | |> Integer.parse |
| | |
Read now
Unlock full access