Controlling the Flow of Impure Functions

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
 

Get Learn Functional Programming with Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.