Controlling the Flow of Impure Functions
Learn to handle the results of impure functions.
We'll cover the following...
Shop checkout
The first strategy for handling unexpected events is to control the flow, as we covered in Chapter 4, Using Pattern Matching to Control the Program Flow. We 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.
$ iex
iex> c("shop.ex")
iex> Shop.checkout(2)
Quantity?
three
'''Output ->
It's not a number
:ok
'''
Try it below:
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 end end
In this example, the program asks the user to enter a number, and we use the function IO.gets/1
to get the user’s input. We know IO.gets/1
is an impure function and it can return anything; for instance, "42\n"
or ...