BinaryWebPark

The Ultimate Guide to Elixir for Object-Oriented Programmers

October 04, 2017

The Ultimate Guide for Making the Jump to Elixir

  <h1 class="subtitle">
    Learn The Basics So You Can Write Production Ready Code
  </h1>

  <h2 class="author">
    Bruce Park
  </h2>
</div>

<h1 class="contents">
  Contents
</h1>

<div id="table_of_contents">
  <ul>
    <li class="chapter-star">
      <a href="#preface" class="heading hyperref">Preface</a>
    </li>
    <li class="chapter">
      <a href="#cha-introduction" class="heading hyperref"><span class="number">Chapter 1 </span>Introduction</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid2" class="heading hyperref"><span class="number">1.1 </span>How I Transitioned to Elixir</a>
        </li>
        <li class="section">
          <a href="#sec-elixir_rising" class="heading hyperref"><span class="number">1.2 </span>Elixir is rising</a>
        </li>
        <li class="section">
          <a href="#cid4" class="heading hyperref"><span class="number">1.3 </span>Welcome</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter1" class="heading hyperref"><span class="number">Chapter 2 </span>How To Install Elixir</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid6" class="heading hyperref"><span class="number">2.1 </span>The Power of Proper Tooling</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid1" class="heading hyperref"><span class="number">2.1.1 </span>And that’s the power of proper tooling</a>
            </li>
            <li class="subsection">
              <a href="#sec-overview_tools" class="heading hyperref"><span class="number">2.1.2 </span>Overview of The Tools</a>
            </li>
            <li class="subsection">
              <a href="#uid6" class="heading hyperref"><span class="number">2.1.3 </span>Option 1: Installing Elixir with Kiex and Kerl</a>
            </li>
            <li class="subsection">
              <a href="#uid7" class="heading hyperref"><span class="number">2.1.4 </span>But I’m used to RVM and other environment managers &#8211; where is the RVM for Elixir?</a>
            </li>
            <li class="subsection">
              <a href="#uid14" class="heading hyperref"><span class="number">2.1.5 </span>Option 2: Installing Elixir with asdf</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid7" class="heading hyperref"><span class="number">2.2 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter2" class="heading hyperref"><span class="number">Chapter 3 </span>Programming Terminology</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid9" class="heading hyperref"><span class="number">3.1 </span>Zen Masters and Adopting the Functional Mind</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid25" class="heading hyperref"><span class="number">3.1.1 </span>Learning Functional Programming Meant I Had to Let Go of the Object Oriented Mind</a>
            </li>
            <li class="subsection">
              <a href="#uid26" class="heading hyperref"><span class="number">3.1.2 </span>How This Immutable Thing Relates to Elixir Processes and “Let It Crash”</a>
            </li>
            <li class="subsection">
              <a href="#sec-object_oriented" class="heading hyperref"><span class="number">3.1.3 </span>Object-Oriented vs Functional</a>
            </li>
            <li class="subsection">
              <a href="#uid28" class="heading hyperref"><span class="number">3.1.4 </span>Modules vs Classes</a>
            </li>
            <li class="subsection">
              <a href="#uid29" class="heading hyperref"><span class="number">3.1.5 </span>Functions: Input X, Receive Y</a>
            </li>
            <li class="subsection">
              <a href="#uid30" class="heading hyperref"><span class="number">3.1.6 </span>Goodbye Inheritance</a>
            </li>
            <li class="subsection">
              <a href="#uid31" class="heading hyperref"><span class="number">3.1.7 </span>Immutability</a>
            </li>
            <li class="subsection">
              <a href="#uid32" class="heading hyperref"><span class="number">3.1.8 </span>How do you do state?</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid10" class="heading hyperref"><span class="number">3.2 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter3" class="heading hyperref"><span class="number">Chapter 4 </span>The Enum Module: The Answer To Ruby’s Enumerable</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid12" class="heading hyperref"><span class="number">4.1 </span>Everyone Loves the Count</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid33" class="heading hyperref"><span class="number">4.1.1 </span>But then I grew up and discovered the Enumerable module…</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#sec-enum_module" class="heading hyperref"><span class="number">4.2 </span>Introducing Enum…</a>
        </li>
        <li class="section">
          <a href="#cid14" class="heading hyperref"><span class="number">4.3 </span>Useful Enum Module Methods</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid34" class="heading hyperref"><span class="number">4.3.1 </span>Enum#at</a>
            </li>
            <li class="subsection">
              <a href="#uid35" class="heading hyperref"><span class="number">4.3.2 </span>Enum#reduce</a>
            </li>
            <li class="subsection">
              <a href="#uid36" class="heading hyperref"><span class="number">4.3.3 </span>Enum#map</a>
            </li>
            <li class="subsection">
              <a href="#uid37" class="heading hyperref"><span class="number">4.3.4 </span>Enum#filter</a>
            </li>
            <li class="subsection">
              <a href="#uid38" class="heading hyperref"><span class="number">4.3.5 </span>Enum#reject</a>
            </li>
            <li class="subsection">
              <a href="#uid39" class="heading hyperref"><span class="number">4.3.6 </span>Enum#all?</a>
            </li>
            <li class="subsection">
              <a href="#uid40" class="heading hyperref"><span class="number">4.3.7 </span>Enum#any?</a>
            </li>
            <li class="subsection">
              <a href="#uid41" class="heading hyperref"><span class="number">4.3.8 </span>Enum#to_list with a range</a>
            </li>
            <li class="subsection">
              <a href="#uid42" class="heading hyperref"><span class="number">4.3.9 </span>Enum#count</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid15" class="heading hyperref"><span class="number">4.4 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter4" class="heading hyperref"><span class="number">Chapter 5 </span>The List Module</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid17" class="heading hyperref"><span class="number">5.1 </span>The Linked List Data Structure and the CSV Reporter</a>
        </li>
        <li class="section">
          <a href="#cid18" class="heading hyperref"><span class="number">5.2 </span>Making a YouTube CSV Reporter</a>
        </li>
        <li class="section">
          <a href="#sec-list_module" class="heading hyperref"><span class="number">5.3 </span>Useful List Module Methods</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid43" class="heading hyperref"><span class="number">5.3.1 </span>List.first</a>
            </li>
            <li class="subsection">
              <a href="#uid44" class="heading hyperref"><span class="number">5.3.2 </span>List.last</a>
            </li>
            <li class="subsection">
              <a href="#uid45" class="heading hyperref"><span class="number">5.3.3 </span>List.flatten</a>
            </li>
            <li class="subsection">
              <a href="#uid46" class="heading hyperref"><span class="number">5.3.4 </span>List.foldl</a>
            </li>
            <li class="subsection">
              <a href="#uid47" class="heading hyperref"><span class="number">5.3.5 </span>List.insert_at</a>
            </li>
            <li class="subsection">
              <a href="#uid48" class="heading hyperref"><span class="number">5.3.6 </span>List.delete_at</a>
            </li>
            <li class="subsection">
              <a href="#uid49" class="heading hyperref"><span class="number">5.3.7 </span>++ and &#8211; &#8211;</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid20" class="heading hyperref"><span class="number">5.4 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter5" class="heading hyperref"><span class="number">Chapter 6 </span>The Map Module</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid22" class="heading hyperref"><span class="number">6.1 </span>The Dictionary</a>
        </li>
        <li class="section">
          <a href="#cid23" class="heading hyperref"><span class="number">6.2 </span>But what about Elixir?</a>
        </li>
        <li class="section">
          <a href="#sec-map_module" class="heading hyperref"><span class="number">6.3 </span>Useful Map Module Methods</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid51" class="heading hyperref"><span class="number">6.3.1 </span>Map.get</a>
            </li>
            <li class="subsection">
              <a href="#uid52" class="heading hyperref"><span class="number">6.3.2 </span>Map.put</a>
            </li>
            <li class="subsection">
              <a href="#uid53" class="heading hyperref"><span class="number">6.3.3 </span>Elixir’s built-in syntax for updating maps</a>
            </li>
            <li class="subsection">
              <a href="#uid54" class="heading hyperref"><span class="number">6.3.4 </span>Map.has_key?</a>
            </li>
            <li class="subsection">
              <a href="#uid55" class="heading hyperref"><span class="number">6.3.5 </span>Map.keys</a>
            </li>
            <li class="subsection">
              <a href="#uid56" class="heading hyperref"><span class="number">6.3.6 </span>Map.values</a>
            </li>
            <li class="subsection">
              <a href="#uid57" class="heading hyperref"><span class="number">6.3.7 </span>Map.replace</a>
            </li>
            <li class="subsection">
              <a href="#uid58" class="heading hyperref"><span class="number">6.3.8 </span>Map.merge</a>
            </li>
            <li class="subsection">
              <a href="#uid59" class="heading hyperref"><span class="number">6.3.9 </span>Map.drop</a>
            </li>
            <li class="subsection">
              <a href="#uid60" class="heading hyperref"><span class="number">6.3.10 </span>Map.to_list</a>
            </li>
            <li class="subsection">
              <a href="#uid61" class="heading hyperref"><span class="number">6.3.11 </span>Map.update</a>
            </li>
            <li class="subsection">
              <a href="#uid62" class="heading hyperref"><span class="number">6.3.12 </span>A word on nested maps</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid25" class="heading hyperref"><span class="number">6.4 </span>Summary</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid63" class="heading hyperref"><span class="number">6.4.1 </span>Footnotes</a>
            </li>
          </ul>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter7" class="heading hyperref"><span class="number">Chapter 7 </span>Conditionals in Elixir</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#sec-map_module" class="heading hyperref"><span class="number">7.1 </span>Conditional Control Flow Structures</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid64" class="heading hyperref"><span class="number">7.1.1 </span>My Overreliance on Cond</a>
            </li>
            <li class="subsection">
              <a href="#uid65" class="heading hyperref"><span class="number">7.1.2 </span>Cond</a>
            </li>
            <li class="subsection">
              <a href="#uid66" class="heading hyperref"><span class="number">7.1.3 </span>Case</a>
            </li>
            <li class="subsection">
              <a href="#uid67" class="heading hyperref"><span class="number">7.1.4 </span>If</a>
            </li>
            <li class="subsection">
              <a href="#uid68" class="heading hyperref"><span class="number">7.1.5 </span>Unless</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid28" class="heading hyperref"><span class="number">7.2 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter8" class="heading hyperref"><span class="number">Chapter 8 </span>Handy Keywords For Working With Modules and Anonymous Functions in Elixir</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid30" class="heading hyperref"><span class="number">8.1 </span>The 2 Hardest Problems in Computer Science</a>
        </li>
        <li class="section">
          <a href="#sec-alias" class="heading hyperref"><span class="number">8.2 </span>Alias and Import</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid70" class="heading hyperref"><span class="number">8.2.1 </span>Alias</a>
            </li>
            <li class="subsection">
              <a href="#uid71" class="heading hyperref"><span class="number">8.2.2 </span>Import</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#sec-module_attributes" class="heading hyperref"><span class="number">8.3 </span>Module Attributes</a>
        </li>
        <li class="section">
          <a href="#sec-anonymous_functions" class="heading hyperref"><span class="number">8.4 </span>Anonymous Functions</a>
        </li>
        <li class="section">
          <a href="#cid34" class="heading hyperref"><span class="number">8.5 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter9" class="heading hyperref"><span class="number">Chapter 9 </span>A Word On Types</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid36" class="heading hyperref"><span class="number">9.1 </span>The First Thing I Do When Getting Started With a Programming Language</a>
        </li>
        <li class="section">
          <a href="#sec-integer_float" class="heading hyperref"><span class="number">9.2 </span>Integers and Floats</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid73" class="heading hyperref"><span class="number">9.2.1 </span>Arithmetic</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#sec-boolean" class="heading hyperref"><span class="number">9.3 </span>Boolean</a>
        </li>
        <li class="section">
          <a href="#cid39" class="heading hyperref"><span class="number">9.4 </span>Atoms</a>
        </li>
        <li class="section">
          <a href="#cid40" class="heading hyperref"><span class="number">9.5 </span>Strings</a>
        </li>
        <li class="section">
          <a href="#cid41" class="heading hyperref"><span class="number">9.6 </span>Lists</a>
        </li>
        <li class="section">
          <a href="#cid42" class="heading hyperref"><span class="number">9.7 </span>Tuples</a>
        </li>
        <li class="section">
          <a href="#cid43" class="heading hyperref"><span class="number">9.8 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter10" class="heading hyperref"><span class="number">Chapter 10 </span>Elixir’s Comprehensions (Not Loops)</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid45" class="heading hyperref"><span class="number">10.1 </span>The Misuse of Elixir’s Comprehensions</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid74" class="heading hyperref"><span class="number">10.1.1 </span>The Purpose of Comprehensions</a>
            </li>
            <li class="subsection">
              <a href="#uid75" class="heading hyperref"><span class="number">10.1.2 </span>A Simple Example of a Comprehension</a>
            </li>
            <li class="subsection">
              <a href="#uid76" class="heading hyperref"><span class="number">10.1.3 </span>Multiple Generators</a>
            </li>
            <li class="subsection">
              <a href="#uid77" class="heading hyperref"><span class="number">10.1.4 </span>Extracting Data Using Pattern Matching</a>
            </li>
            <li class="subsection">
              <a href="#uid78" class="heading hyperref"><span class="number">10.1.5 </span>Filtering in Comprehensions</a>
            </li>
            <li class="subsection">
              <a href="#uid79" class="heading hyperref"><span class="number">10.1.6 </span>Into a Map</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid46" class="heading hyperref"><span class="number">10.2 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter11" class="heading hyperref"><span class="number">Chapter 11 </span>Strings in Elixir</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid48" class="heading hyperref"><span class="number">11.1 </span>When IO.inspect Let Me Down With a Character List</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid80" class="heading hyperref"><span class="number">11.1.1 </span>But first, we need to talk about binaries</a>
            </li>
            <li class="subsection">
              <a href="#uid81" class="heading hyperref"><span class="number">11.1.2 </span>Let’s see how to represent a binary with actual code</a>
            </li>
            <li class="subsection">
              <a href="#uid82" class="heading hyperref"><span class="number">11.1.3 </span>What does this have to do with strings again?</a>
            </li>
            <li class="subsection">
              <a href="#uid83" class="heading hyperref"><span class="number">11.1.4 </span>Single versus double quotes</a>
            </li>
            <li class="subsection">
              <a href="#uid84" class="heading hyperref"><span class="number">11.1.5 </span>Properties of double-quoted strings.</a>
            </li>
            <li class="subsection">
              <a href="#uid87" class="heading hyperref"><span class="number">11.1.6 </span>Single-quoted strings are character lists</a>
            </li>
            <li class="subsection">
              <a href="#sec-heredocs" class="heading hyperref"><span class="number">11.1.7 </span>Heredocs</a>
            </li>
            <li class="subsection">
              <a href="#uid91" class="heading hyperref"><span class="number">11.1.8 </span>Some Interesting Reference Links</a>
            </li>
          </ul>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter11" class="heading hyperref"><span class="number">Chapter 12 </span>What Open Source Taught Me About the Basics of Documentation In Elixir</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#sec-timex" class="heading hyperref"><span class="number">12.1 </span>Looking at Timex</a>
        </li>
        <li class="section">
          <a href="#sec-documentation_first_class" class="heading hyperref"><span class="number">12.2 </span>The Philosophy of Documentation as a First Class Citizen</a>
        </li>
        <li class="section">
          <a href="#sec-markdown" class="heading hyperref"><span class="number">12.3 </span>The Syntax for Writing Documentation &#8211; Markdown</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid92" class="heading hyperref"><span class="number">12.3.1 </span>Headings</a>
            </li>
            <li class="subsection">
              <a href="#uid93" class="heading hyperref"><span class="number">12.3.2 </span>Code blocks</a>
            </li>
            <li class="subsection">
              <a href="#uid94" class="heading hyperref"><span class="number">12.3.3 </span>Lists</a>
            </li>
            <li class="subsection">
              <a href="#uid103" class="heading hyperref"><span class="number">12.3.4 </span>Basic Styling of Text</a>
            </li>
            <li class="subsection">
              <a href="#uid104" class="heading hyperref"><span class="number">12.3.5 </span>External Hyperlinks</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#sec-elixir_documentation" class="heading hyperref"><span class="number">12.4 </span>Documenting Your Elixir Code</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid105" class="heading hyperref"><span class="number">12.4.1 </span>Documenting Modules</a>
            </li>
            <li class="subsection">
              <a href="#uid110" class="heading hyperref"><span class="number">12.4.2 </span>Documenting Functions</a>
            </li>
            <li class="subsection">
              <a href="#uid111" class="heading hyperref"><span class="number">12.4.3 </span>A Word on Documenting Private Functions</a>
            </li>
            <li class="subsection">
              <a href="#uid112" class="heading hyperref"><span class="number">12.4.4 </span>Typespecs</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid54" class="heading hyperref"><span class="number">12.5 </span>Writing Documentation Tests in Phoenix and Elixir</a>
        </li>
        <li class="section">
          <a href="#cid55" class="heading hyperref"><span class="number">12.6 </span>Documentation NestedFilter and Digger</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid117" class="heading hyperref"><span class="number">12.6.1 </span>Summary</a>
            </li>
          </ul>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter_kernels" class="heading hyperref"><span class="number">Chapter 13 </span>Chapter 12 A Tour of The Kernel Module</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid57" class="heading hyperref"><span class="number">13.1 </span>Where does to_atom come from?</a>
        </li>
        <li class="section">
          <a href="#cid58" class="heading hyperref"><span class="number">13.2 </span>Diving Into Kernel’s Interesting Functions</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid118" class="heading hyperref"><span class="number">13.2.1 </span>The is_* functions</a>
            </li>
            <li class="subsection">
              <a href="#uid133" class="heading hyperref"><span class="number">13.2.2 </span>Binaries and Bitstrings: A Simple Explanation</a>
            </li>
            <li class="subsection">
              <a href="#uid134" class="heading hyperref"><span class="number">13.2.3 </span>The data structure functions</a>
            </li>
            <li class="subsection">
              <a href="#uid148" class="heading hyperref"><span class="number">13.2.4 </span>The math functions</a>
            </li>
            <li class="subsection">
              <a href="#uid157" class="heading hyperref"><span class="number">13.2.5 </span>Miscellaneous functions</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid59" class="heading hyperref"><span class="number">13.3 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cha-chapter13" class="heading hyperref"><span class="number">Chapter 14 </span>Digging Into Protocols</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid61" class="heading hyperref"><span class="number">14.1 </span>Pattern Matching: When You Have a Hammer Everything Looks Like a Nail</a>
        </li>
        <li class="section">
          <a href="#cid62" class="heading hyperref"><span class="number">14.2 </span>Enter Protocols: What Are They?</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid163" class="heading hyperref"><span class="number">14.2.1 </span>Ok, so what is polymorphism?</a>
            </li>
            <li class="subsection">
              <a href="#uid169" class="heading hyperref"><span class="number">14.2.2 </span>Protocols Defined</a>
            </li>
            <li class="subsection">
              <a href="#uid171" class="heading hyperref"><span class="number">14.2.3 </span>Practically speaking, how do you use protocols in Elixir?</a>
            </li>
            <li class="subsection">
              <a href="#uid172" class="heading hyperref"><span class="number">14.2.4 </span>A Case Study On Using Polymorphism: Rewriting the Digger.Atomizer Module Using Protocols</a>
            </li>
            <li class="subsection">
              <a href="#uid173" class="heading hyperref"><span class="number">14.2.5 </span>Step 1: Define Your Protocol with defprotocol</a>
            </li>
            <li class="subsection">
              <a href="#uid174" class="heading hyperref"><span class="number">14.2.6 </span>Step 2: Define Your Implementation with defimpl</a>
            </li>
            <li class="subsection">
              <a href="#uid175" class="heading hyperref"><span class="number">14.2.7 </span>Step 3: Implement Any as a Fallback</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid63" class="heading hyperref"><span class="number">14.3 </span>Best practices for organizing protocols and their implementation?</a>
        </li>
        <li class="section">
          <a href="#cid64" class="heading hyperref"><span class="number">14.4 </span>Other Tips</a>
        </li>
        <li class="section">
          <a href="#cid65" class="heading hyperref"><span class="number">14.5 </span>Summary</a>
        </li>
        <li class="section">
          <a href="#cid66" class="heading hyperref"><span class="number">14.6 </span>Resources:</a>
        </li>
        <li class="section">
          <a href="#cid67" class="heading hyperref"><span class="number">14.7 </span>Footnotes:</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cid68" class="heading hyperref"><span class="number">Chapter 15 </span>Behaviors and Protocols</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid69" class="heading hyperref"><span class="number">15.1 </span>And what does this have to do with behaviors?</a>
        </li>
        <li class="section">
          <a href="#cid70" class="heading hyperref"><span class="number">15.2 </span>Defining Behaviors</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid180" class="heading hyperref"><span class="number">15.2.1 </span>In coded English, a behavior does the following</a>
            </li>
            <li class="subsection">
              <a href="#uid181" class="heading hyperref"><span class="number">15.2.2 </span>Use the @callback attribute to specify the functions that are part of the @behavior contract</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid71" class="heading hyperref"><span class="number">15.3 </span>Dynamic Dispatching</a>
        </li>
        <li class="section">
          <a href="#cid72" class="heading hyperref"><span class="number">15.4 </span>Relation to Protocols</a>
        </li>
        <li class="section">
          <a href="#cid73" class="heading hyperref"><span class="number">15.5 </span>Summary</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid183" class="heading hyperref"><span class="number">15.5.1 </span>Footnotes</a>
            </li>
          </ul>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cid74" class="heading hyperref"><span class="number">Chapter 16 </span>Guards</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid75" class="heading hyperref"><span class="number">16.1 </span>What is a guard?</a>
        </li>
        <li class="section">
          <a href="#cid76" class="heading hyperref"><span class="number">16.2 </span>Why Use a Guard?</a>
        </li>
        <li class="section">
          <a href="#cid77" class="heading hyperref"><span class="number">16.3 </span>Types of Functions You Can Use With Guards</a>
        </li>
        <li class="section">
          <a href="#cid78" class="heading hyperref"><span class="number">16.4 </span>Why You Can’t Use Custom Functions with Guards</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid184" class="heading hyperref"><span class="number">16.4.1 </span>Operators and Functions You Can Use in Guards</a>
            </li>
            <li class="subsection">
              <a href="#uid187" class="heading hyperref"><span class="number">16.4.2 </span>Why You Can’t Use Custom Functions With Guards</a>
            </li>
            <li class="subsection">
              <a href="#uid189" class="heading hyperref"><span class="number">16.4.3 </span>Or Can You Use Custom Functions?</a>
            </li>
            <li class="subsection">
              <a href="#uid191" class="heading hyperref"><span class="number">16.4.4 </span>Introducing defguard(p) in Elixir 1.6</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid79" class="heading hyperref"><span class="number">16.5 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cid80" class="heading hyperref"><span class="number">Chapter 17 </span>IO and Files</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid81" class="heading hyperref"><span class="number">17.1 </span>File Module and Functions</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid193" class="heading hyperref"><span class="number">17.1.1 </span>Bang and Non-Bang Function API</a>
            </li>
            <li class="subsection">
              <a href="#uid194" class="heading hyperref"><span class="number">17.1.2 </span>File Function Examples</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid82" class="heading hyperref"><span class="number">17.2 </span>Path Module</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid204" class="heading hyperref"><span class="number">17.2.1 </span>Path Function Examples</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid83" class="heading hyperref"><span class="number">17.3 </span>IO Module and Functions</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid210" class="heading hyperref"><span class="number">17.3.1 </span>IO Function Examples</a>
            </li>
          </ul>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cid84" class="heading hyperref"><span class="number">Chapter 18 </span>Building a Random Image CLI Loader</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid85" class="heading hyperref"><span class="number">18.1 </span>Case Study: Building a Random Image CLI Loader with EScript</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid216" class="heading hyperref"><span class="number">18.1.1 </span>Step 1: Initialize a mix application</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid86" class="heading hyperref"><span class="number">18.2 </span>Step 2: Add yaml-elixir and Write Tests</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid218" class="heading hyperref"><span class="number">18.2.1 </span>Step 3: Setup Yaml Structure / File</a>
            </li>
            <li class="subsection">
              <a href="#uid219" class="heading hyperref"><span class="number">18.2.2 </span>Step 4: Open Images</a>
            </li>
            <li class="subsection">
              <a href="#uid220" class="heading hyperref"><span class="number">18.2.3 </span>Step 5: Convert to Escript</a>
            </li>
            <li class="subsection">
              <a href="#uid224" class="heading hyperref"><span class="number">18.2.4 </span>Step 6: Run the CLI program</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid87" class="heading hyperref"><span class="number">18.3 </span>Summary</a>
        </li>
      </ul>
    </li>

    <li class="chapter">
      <a href="#cid88" class="heading hyperref"><span class="number">Chapter 19 </span>Everyone Makes Mistakes: Errors in Elixir</a>
    </li>
    <li>
      <ul>
        <li class="section">
          <a href="#cid89" class="heading hyperref"><span class="number">19.1 </span>Elixir Philosophy: Let It Crash</a>
        </li>
        <li class="section">
          <a href="#cid90" class="heading hyperref"><span class="number">19.2 </span>Conventions</a>
        </li>
        <li class="section">
          <a href="#cid91" class="heading hyperref"><span class="number">19.3 </span>Error Handling Keywords</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid225" class="heading hyperref"><span class="number">19.3.1 </span>try</a>
            </li>
            <li class="subsection">
              <a href="#uid226" class="heading hyperref"><span class="number">19.3.2 </span>catch</a>
            </li>
            <li class="subsection">
              <a href="#uid227" class="heading hyperref"><span class="number">19.3.3 </span>throw</a>
            </li>
            <li class="subsection">
              <a href="#uid228" class="heading hyperref"><span class="number">19.3.4 </span>rescue</a>
            </li>
            <li class="subsection">
              <a href="#uid229" class="heading hyperref"><span class="number">19.3.5 </span>raise</a>
            </li>
            <li class="subsection">
              <a href="#uid230" class="heading hyperref"><span class="number">19.3.6 </span>after</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid92" class="heading hyperref"><span class="number">19.4 </span>Examples of Try/Rescue</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid231" class="heading hyperref"><span class="number">19.4.1 </span>Example From the Phoenix Framework</a>
            </li>
          </ul>
        </li>

        <li class="section">
          <a href="#cid93" class="heading hyperref"><span class="number">19.5 </span>Examples of Throw/Catch</a>
        </li>
        <li class="section">
          <a href="#cid94" class="heading hyperref"><span class="number">19.6 </span>Examples of Try/After</a>
        </li>
        <li class="section">
          <a href="#cid95" class="heading hyperref"><span class="number">19.7 </span>Scope in Try/Rescue/Catch/After</a>
        </li>
        <li class="section">
          <a href="#cid96" class="heading hyperref"><span class="number">19.8 </span>Summary</a>
        </li>
        <li>
          <ul>
            <li class="subsection">
              <a href="#uid235" class="heading hyperref"><span class="number">19.8.1 </span>Footnotes</a>
            </li>
          </ul>
        </li>
      </ul>
    </li>
  </ul>
</div>

<div class="chapter-star" id="preface">
  <h1>
    <a href="#preface" class="heading hyperref">Preface</a>
  </h1>

  <p class="noindent">
    Learning in layers…
  </p>

  <p>
    I started out with Ruby.<span class="intersentencespace"></span> When Elixir came out I took a peek and was interested.<span class="intersentencespace"></span> Slowly, I began to make time for it with my Ruby day job.<span class="intersentencespace"></span> Eventually, I transitioned out of my Ruby job and found an Elixir one.
  </p>

  <p>
    This prediction might be completely wrong, but I think Elixir is the future.
  </p>

  <p>
    Either way, I hope you enjoy the book and please don’t hesitate to contact me with any questions or any issue at all at bruce@binarywebpark.com.
  </p>
</div>

Last Updated: 04/09/2018 Monday

If you’re new to Elixir and have been wanting to learn it quickly, check out the Elixir Core Video course (now at special Beta launch pricing). In just 30 minutes a day, you can teach yourself the fundamentals of Elixir. Click on the image below to enroll today!

Chapter 1 Introduction

<p class="noindent">
  You’ve got a full time day job working in an object-oriented language like Ruby, Java, or C++ but you’ve been wanting to come up to speed on Elixir.<span class="intersentencespace"></span> If you’ve got a family or other pressing commitments, taking hours out of your week to read blog posts or spending time to contribute to open source could be a deal breaker for you.
</p>

1.1 How I Transitioned to Elixir

<p class="noindent">
  I got started in Elixir by doing simple code katas and doing some minor open source contributions.<span class="intersentencespace"></span> Then I somehow found a day job in Elixir, mostly doing web application development type work.<span class="intersentencespace"></span> So having been through hours of blog posts and reading different books, I’ve started distilling it down into the most efficient pathway to go from an object-oriented language to Elixir.
</p>

1.2 Elixir is rising

<p class="noindent">
  But perhaps you’re interested in functional programming and you can see that Elixir is rising.<span class="intersentencespace"></span> Plus, the advantages it has for solving certain classes of problems really appeals to you.<span class="intersentencespace"></span> So that’s why I created this course.<span class="intersentencespace"></span> No, I’m not promising you can go through it in “30 days” and become an Elixir expert.<span class="intersentencespace"></span> But I am confident you will get the tools you need to understand the basics of the language, avoid the hours of pitfalls I had while learning the language coming from an object-oriented background in Ruby, and get you on your way.
</p>

<p>
  I’m also confident if you spend 30 minutes a day going over this stuff, you can do it rather quickly.<span class="intersentencespace"></span> Certaintly, you can do it more quickly than by spending hours reading random blog posts and books.
</p>

1.3 Welcome

<p class="noindent">
  So welcome aboard.<span class="intersentencespace"></span> Don’t hesitate to ask me questions as you go through the course and I hope you enjoy it!
</p>

<p>
  May the 1’s and 0’s be with you,
</p>

<p>
  Bruce Park
</p>

2.1 The Power of Proper Tooling

<p class="noindent">
  As I began to acquire more expertise and experience in programming, I realized that in some ways, 50% of the battle in getting started with learning a new technology stack is getting setup with the right tooling.
</p>

<p>
  I still remember the first time I setup a shortcut for setting up <code>git status</code>.<span class="intersentencespace"></span> I added a shortcut with <code>git st</code>.<span class="intersentencespace"></span> One of my coworkers showed me a shortcut <code>gs</code> &#8211; even shorter!<span class="intersentencespace"></span> Holy cow, what a difference having not to type those last few characters makes!
</p>

<div id="uid1" data-tralics-id="uid1" class="subsection" data-number="2.1.1">
  <h3>
    <a href="#uid1" class="heading hyperref"><span class="number">2.1.1 </span>And that’s the power of proper tooling</a>
  </h3>

  <p class="noindent">
    Proper tooling makes you more productive and makes programming more fun.<span class="intersentencespace"></span> I find having a proper environment manager to help you manage different releases of a language, makes it easy to test out different versions of the language.<span class="intersentencespace"></span> This especially holds true for an up and coming language like Elixir.<span class="intersentencespace"></span> So let’s dive into the tools!
  </p>
</div>

<div id="sec-overview_tools" data-tralics-id="uid2" class="subsection" data-number="2.1.2">
  <h3>
    <a href="#sec-overview_tools" class="heading hyperref"><span class="number">2.1.2 </span>Overview of The Tools</a>
  </h3>

  <p class="noindent">
    Let’s go over some tools you can use to manage your Elixir (and Erlang) installation.<span class="intersentencespace"></span> Since Elixir runs on top of Erlang, you’ll want a way to easily manage both Elixir and Erlang installations.<span class="intersentencespace"></span> Hopefully by the end of this, you’ll have everything setup and be ready to dive into the wonderful world of Elixir.
  </p>

  <div id="uid3" data-tralics-id="uid3" class="subsubsection" data-number="2.1.2.1">
    <h4>
      <a href="#uid3" class="heading">Kiex</a>
    </h4>

    <p class="noindent">
      If you’ve used a Ruby version manager like RVM or chruby, then you can think of <a href="https://github.com/taylor/kiex" target="_blank" rel="noopener">kiex</a> as being equivalent to that.<span class="intersentencespace"></span> Kiex is a handy little tool to let you easily install and/or switch between Elixir versions.<span class="intersentencespace"></span> And as Elixir is a fairly new language, it’s constantly being updated.
    </p>
  </div>

  <div id="uid4" data-tralics-id="uid4" class="subsubsection" data-number="2.1.2.2">
    <h4>
      <a href="#uid4" class="heading">Kerl</a>
    </h4>

    <p class="noindent">
      <a href="https://github.com/kerl/kerl" target="_blank" rel="noopener">Kerl</a> is the tool that lets you easily switch out and build different Erlang versions.<span class="intersentencespace"></span> It’s a pretty handy tool to have since newer versions of Elixir keep using newer versions of Erlang.<span class="intersentencespace"></span> For example, due to some recent changes in the way Elixir handles debugging messages, Elixir 1.5 lets you take advantage of this functionality but only if you have Erlang 20 installed (at the time of this writing).
    </p>
  </div>

  <div id="uid5" data-tralics-id="uid5" class="subsubsection" data-number="2.1.2.3">
    <h4>
      <a href="#uid5" class="heading">asdf</a>
    </h4>

    <p class="noindent">
      I would be somewhat remiss if I didn’t mention <a href="https://github.com/asdf-vm/asdf" target="_blank" rel="noopener">asdf</a>, as it is a pretty handy tool that lets you install more than just Elixir.<span class="intersentencespace"></span> Asdf is “an extendable version manager” and it supports Erlang, Elixir, Ruby, and more languages.<span class="intersentencespace"></span> In my experience you end up with a <em>.tool-versions</em> file in your code repositories where you’re using the tool.
    </p>

    <p>
      But that’s a minor thing in my opinion.<span class="intersentencespace"></span> Overall, if I hadn’t done kiex and kerl, I might have gone with asdf.<span class="intersentencespace"></span> The point is, “you do you”.<span class="intersentencespace"></span> Pick what is most comfortable to you.
    </p>
  </div>
</div>

<div id="uid6" data-tralics-id="uid6" class="subsection" data-number="2.1.3">
  <h3>
    <a href="#uid6" class="heading hyperref"><span class="number">2.1.3 </span>Option 1: Installing Elixir with Kiex and Kerl</a>
  </h3>

  <p class="noindent">
    I’m going to give you a step-by-step overview of how to install Elixir with kiex and kerl.
  </p>

  <p>
    If you’re used to using Ruby in your day job, you’ve probably come to appreciate the Ruby ecosystem of tools to get setup and running &#8211; bundler and rvm (or chruby or rbenv depending on your preferences).
  </p>
</div>

<div id="uid7" data-tralics-id="uid7" class="subsection" data-number="2.1.4">
  <h3>
    <a href="#uid7" class="heading hyperref"><span class="number">2.1.4 </span>But I’m used to RVM and other environment managers &#8211; where is the RVM for Elixir?</a>
  </h3>

  <p class="noindent">
    It turns out there’s a few options for Elixir.<span class="intersentencespace"></span> As I stated before, I ended up choosing Kerl and Kiex.<span class="intersentencespace"></span> Here is how I installed it on my Ubuntu desktop and Mac OSX laptop.
  </p>

  <div id="uid8" data-tralics-id="uid8" class="subsubsection" data-number="2.1.4.1">
    <h4>
      <a href="#uid8" class="heading">Step 1 &#8211; Installing Kiex</a>
    </h4>

    <p class="noindent">
      Kiex is like RVM in that it allows you to switch between different Elixir versions and build them.<span class="intersentencespace"></span> Below is a set of instructions you enter at the command line.
    </p>

    <div class="code">
      <div class="highlight">
        <pre>$ curl -sSL https://raw.githubusercontent.com/taylor/kiex/master/install | bash -s

In your .bashrc (or .zshrc if you use z shell) file, add the following line:

[[ -s “$HOME/.kiex/scripts/kiex” ]] && source ”$HOME/.kiex/scripts/kiex”

  <div id="uid9" data-tralics-id="uid9" class="subsubsection" data-number="2.1.4.2">
    <h4>
      <a href="#uid9" class="heading">Step 2 &#8211; Installing Kerl, Elixir and Erlang</a>
    </h4>

    <p class="noindent">
      Because Elixir runs on top of Erlang, you need a way to build and install Erlang/OTP instances.
    </p>

    <p>
      Below is a set of instructions you enter at the command line.
    </p>

    <div class="code">
      <div class="highlight">
        <pre>$ mkdir ~/.kerl

$ cd ~/.kerl $ curl -O https://raw.githubusercontent.com/yrashk/kerl/master/kerl $ chmod a+x kerl $ kerl list releases $ kiex list known

can now use elixir

$ kiex install 1.5.2 $ kiex use 1.5.2 $ mkdir ~/erlanginstall/20.0 $ kerl build 20.0 20.0 $ kerl install 20.0 ~/erlanginstall/20.0

    <p>
      You can activate this installation running the following command:
    </p>

    <div class="code">
      <div class="highlight">
        <pre>$ . ~/erlang_install/20.0/activate
In .bashrc (or .zshrc if you use z shell), add the following:

    <div class="code">
      <div class="highlight">
        <pre>$ . ~/erlang_install/20.0/activate
    <p>
      Later on, you can leave the installation by typing: <em>kerl_deactivate</em>
    </p>

    <p>
      You can delete a build with <em>kerl delete build 20.0</em>.
    </p>

    <p>
      Source: <a href="https://github.com/yrashk/kerl" target="_blank" rel="noopener">https://github.com/yrashk/kerl</a> &#8211; follow instructions and add <code>export PATH="$PATH:$HOME/.kerl"</code>
    </p>

    <p>
      to .bashrc (or .zshrc or any other .rc file)
    </p></div3>
  </div>

  <div id="uid11" data-tralics-id="uid11" class="subsubsection" data-number="2.1.4.3">
    <h4>
      <a href="#uid11" class="heading">Troubleshooting</a>
    </h4>

    <p class="noindent">
      If you get a debug message such as:
    </p>

    <p>
      <code>Kiex sourcing line not found in &lt;span class="inline_math">\( \sim  \)&lt;/span>/.bashrc, &lt;span class="inline_math">\( \sim  \)&lt;/span>/.bash_profile, &lt;span class="inline_math">\( \sim  \)&lt;/span>/.profile, &lt;span class="inline_math">\( \sim  \)&lt;/span>/.zshrc, or &lt;span class="inline_math">\( \sim  \)&lt;/span>/.zsh_profile</code>
    </p>
  </div>

  <div id="uid12" data-tralics-id="uid12" class="subsubsection" data-number="2.1.4.4">
    <h4>
      <a href="#uid12" class="heading">Add the following to your shell’s config file (.bashrc/.zshrc/.cshrc):</a>
    </h4>

    <p class="noindent">
      <code>[[ -s "$HOME/.kiex/scripts/kiex" ]] && source "$HOME/.kiex/scripts/kiex"</code>
    </p>
  </div>

  <div id="uid13" data-tralics-id="uid13" class="subsubsection" data-number="2.1.4.5">
    <h4>
      <a href="#uid13" class="heading">Other useful commands</a>
    </h4>

    <p class="noindent">
      <div class="code">
        <div class="highlight">
          <pre><span class="go">kerl list installations</span>

erl version

      <p>
        <em>erl version</em> will list the Erlang version, you will see something like: <em>Erlang (SMP,ASYNC_THREADS,HIPE) (BEAM) emulator version 5.8.3</em>
      </p></div> </div>

      <div id="uid14" data-tralics-id="uid14" class="subsection" data-number="2.1.5">
        <h3>
          <a href="#uid14" class="heading hyperref"><span class="number">2.1.5 </span>Option 2: Installing Elixir with asdf</a>
        </h3>

        <p class="noindent">
          The other option is to install Elixir with asdf.
        </p>

        <p>
          In terms of version numbers for Elixr and Erlang, version numbers should be the ones you want to use.<span class="intersentencespace"></span> Here I do it with the latest ones available at the moment of writing.
        </p>

        <p>
          Anyway, if you intend to work with several versions of erlang or elixir at the same time, or you are tied to a specific version, you will need to compile it yourself.<span class="intersentencespace"></span> Then <em>asdf</em> is your best friend.
        </p>

        <div id="uid15" data-tralics-id="uid15" class="subsubsection" data-number="2.1.5.1">
          <h4>
            <a href="#uid15" class="heading">Step 1 &#8211; On Linux, install needed system packages</a>
          </h4>

          <p class="noindent">
            On Linux, you may have to install the following packages if you don’t have them already.
          </p><div3 id="uid16" data-tralics-id="uid16" data-number="">Fedora</p>

          <div class="code">
            <div class="highlight">
              <pre>$ sudo dnf install make automake gcc gcc-c++ kernel-devel git wget openssl-devel ncurses-devel wxBase3 wxGTK3-devel m4
Ubuntu

          <div class="code">
            <div class="highlight">
              <pre>$ sudo apt-get install build-essential git wget libssl-dev libreadline-dev libncurses5-dev zlib1g-dev m4 curl wx-common libwxgtk3.0-dev autoconf
        <div id="uid18" data-tralics-id="uid18" class="subsubsection" data-number="2.1.5.2">
          <h4>
            <a href="#uid18" class="heading">Step 1a &#8211; On MacOSX, install needed system packages (via homebrew)</a>
          </h4>

          <p class="noindent">
            <div class="code">
              <div class="highlight">
                <pre>coreutils automake autoconf openssl libyaml readline libxslt libtool unixodbc
            <div id="uid19" data-tralics-id="uid19" class="subsubsection" data-number="2.1.5.3">
              <h4>
                <a href="#uid19" class="heading">Step 2 &#8211; Install asdf and its plugins</a>
              </h4>

              <p class="noindent">
                <em>asdf</em> lives in https://github.com/asdf-vm/asdf
              </p>

              <p>
                Follow its installation instructions, which at the moment of writing were:
              </p>

              <div class="code">
                <div class="highlight">
                  <pre>$ git clone https://github.com/asdf-vm/asdf.git ~/.asdf --branch v0.4.3
            <div id="uid20" data-tralics-id="uid20" class="subsubsection" data-number="2.1.5.4">
              <h4>
                <a href="#uid20" class="heading">For Ubuntu, other linux distros, or MacOSX</a>
              </h4>

              <p class="noindent">
                <div class="code">
                  <div class="highlight">
                    <pre>$ echo '. $HOME/.asdf/asdf.sh' >> ~/.bashrc

$ echo ‘. $HOME/.asdf/completions/asdf.bash’ >> ~/.bashrc

                <div id="uid21" data-tralics-id="uid21" class="subsubsection" data-number="2.1.5.5">
                  <h4>
                    <a href="#uid21" class="heading">If you’re using Zsh shell, use these lines</a>
                  </h4>

                  <p class="noindent">
                    <div class="code">
                      <div class="highlight">
                        <pre>$ echo -e '\n. $HOME/.asdf/asdf.sh' >> ~/.zshrc

$ echo -e ‘\n. $HOME/.asdf/completions/asdf.bash’ >> ~/.zshrc

Step 2a – On a new terminal, install Erlang and Elixir plugins:

                  <div class="code">
                    <div class="highlight">
                      <pre>asdf plugin-add erlang https://github.com/asdf-vm/asdf-erlang.git

asdf plugin-add elixir https://github.com/asdf-vm/asdf-elixir.git

                <div id="uid23" data-tralics-id="uid23" class="subsubsection" data-number="2.1.5.6">
                  <h4>
                    <a href="#uid23" class="heading">Step 3 &#8211; Install Erlang and Elixir</a>
                  </h4>

                  <p class="noindent">
                    <div class="code">
                      <div class="highlight">
                        <pre>asdf install erlang 20.2

asdf install elixir 1.6.4-otp-20

                    <p>
                      Then set them as the global version:
                    </p>

                    <div class="code">
                      <div class="highlight">
                        <pre>asdf global erlang 20.2

asdf global elixir 1.6.4-otp-20

                    <p>
                      Now you can open a new terminal and try <code>erl</code>:
                    </p>

                    <div class="code">
                      <div class="highlight">
                        <pre>$ erl

Erlang/OTP 20 [erts-9.0][source] [64-bit][smp:4:4] [ds:4:4:10][async-threads:10] [hipe][kernel-poll:false]

Eshell V9.0 (abort with ^G) 1>

                    <p>
                      Or start Erlang Observer by <code>erl -s observer start</code>.
                    </p>

                    <p>
                      And you can try ‘iex’:
                    </p>

                    <div class="code">
                      <div class="highlight">
                        <pre>$ iex

Erlang/OTP 20 [erts-9.0][source] [64-bit][smp:4:4] [ds:4:4:10][async-threads:10] [hipe][kernel-poll:false]

Interactive Elixir (1.5.0) - press Ctrl+C to exit (type h() ENTER for help) iex(1)>

                    <p>
                      Use <code>asdf</code> <code>.tool-versions</code> file to manage which version is active on each of your projects.
                    </p>

                    <p>
                      Enjoy!
                    </p></div> </div> </div>

                    <div id="cid7" data-tralics-id="cid7" class="section" data-number="2.2">
                      <h2>
                        <a href="#cid7" class="heading hyperref"><span class="number">2.2 </span>Summary</a>
                      </h2>

                      <p class="noindent">
                        As I said before, 50% of the battle in getting started with learning a new technology stack is getting setup with the right tooling.<span class="intersentencespace"></span> It’s more productive and more fun to get started the right way.
                      </p>

                      <p>
                        The tools are always changing in the programming landscape, so if you find a cool tool you like, I do hope you’ll share it with me so I can keep this guide updated for others as well as yourself!
                      </p>
                    </div>

                    <div id="cha-chapter2" data-tralics-id="cid8" class="chapter" data-number="3">
                      <h1>
                        <a href="#cha-chapter2" class="heading hyperref"><span class="number">Chapter 3 </span>Programming Terminology</a>
                      </h1>
                    </div>

                    <div id="cid9" data-tralics-id="cid9" class="section" data-number="3.1">
                      <h2>
                        <a href="#cid9" class="heading hyperref"><span class="number">3.1 </span>Zen Masters and Adopting the Functional Mind</a>
                      </h2>

                      <p class="noindent">
                        So let me tell you a story.<sup id="cha-3_footnote-ref-1" class="footnote"><a href="#cha-3_footnote-1">1</a></sup>
                      </p>

                      <blockquote class="quotation">
                        <p class="quote">
                          Once, a long time ago, there was a wise Zen master.<span class="intersentencespace"></span> People from far and near would seek his counsel and ask for his wisdom.<span class="intersentencespace"></span> Many would come and ask him to teach them, enlighten them in the way of Zen.<span class="intersentencespace"></span> He seldom turned any away.<span class="intersentencespace"></span> One day an important man, a man used to command and obedience came to visit the master.<span class="intersentencespace"></span> “I have come today to ask you to teach me about Zen.<span class="intersentencespace"></span> Open my mind to enlightenment.”<span class="intersentencespace"></span> The tone of the important man’s voice was one used to getting his own way.<span class="intersentencespace"></span> The Zen master smiled and said that they should discuss the matter over a cup of tea.<span class="intersentencespace"></span> When the tea was served the master poured his visitor a cup.<span class="intersentencespace"></span> He poured and he poured and the tea rose to the rim and began to spill over the table and finally onto the robes of the wealthy man.<span class="intersentencespace"></span> Finally the visitor shouted, “Enough.<span class="intersentencespace"></span> You are spilling the tea all over.<span class="intersentencespace"></span> Can’t you see the cup is full?”<span class="intersentencespace"></span> The master stopped pouring and smiled at his guest.<span class="intersentencespace"></span> “You are like this tea cup, so full that nothing more can be added.<span class="intersentencespace"></span> Come back to me when the cup is empty.<span class="intersentencespace"></span> Come back to me with an empty mind.”<span class="intersentencespace"></span>
                        </p>
                      </blockquote>

                      <div id="uid25" data-tralics-id="uid25" class="subsection" data-number="3.1.1">
                        <h3>
                          <a href="#uid25" class="heading hyperref"><span class="number">3.1.1 </span>Learning Functional Programming Meant I Had to Let Go of the Object Oriented Mind</a>
                        </h3>

                        <p class="noindent">
                          In Elixir, there is no such thing as “objects”.<span class="intersentencespace"></span> There’s no such thing as “classes”.<span class="intersentencespace"></span> Most importantly, you’ll hear a phrase “data is immutable”.
                        </p>

                        <p>
                          This means that values in a certain memory location don’t change.<span class="intersentencespace"></span> Often, you will see something like:
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>v = 2
                        <p>
                          This is referred to as “binding” the value 2 to v.<span class="intersentencespace"></span> If you then did <code>v = 3</code>, this simply points v to a memory location that contains the value 3.<span class="intersentencespace"></span> The memory location that contains the value 2 still exists.<span class="intersentencespace"></span> That’s why you refer to this operation as “rebinding the variable v to the value 3” instead of “assigning 3 to v” the way you do in object oriented languages.
                        </p>

                        <p>
                          From a programming standpoint, now both 2 and 3 are in memory until they are garbage collected.
                        </p>
                      </div>

                      <div id="uid26" data-tralics-id="uid26" class="subsection" data-number="3.1.2">
                        <h3>
                          <a href="#uid26" class="heading hyperref"><span class="number">3.1.2 </span>How This Immutable Thing Relates to Elixir Processes and “Let It Crash”</a>
                        </h3>

                        <p class="noindent">
                          If you hang around the Elixir community long enough, you’ll hear the phrase “let it crash”, meaning to let a process (containing data) just crash if an unexpected error happens.<span class="intersentencespace"></span> A process never has access to another process’s data (and hence state), and so you don’t have to worry that losing one process will affect behavior or data in another process.<span class="intersentencespace"></span> It’s a recipe for a more stable system.
                        </p>

                        <p>
                          In object-oriented languages (like Java), where data can be mutated across threads, one thread can be updating while another can be reading from a data store, and so you need to worry about “protecting” state during concurrent operations.
                        </p>

                        <p>
                          The beauty and implication of the “rebinding” of the variable v, is that you have a guarantee that your data in a memory location won’t change.<span class="intersentencespace"></span> Said another way, the “data is immutable”.
                        </p>
                      </div>

                      <div id="sec-object_oriented" data-tralics-id="uid27" class="subsection" data-number="3.1.3">
                        <h3>
                          <a href="#sec-object_oriented" class="heading hyperref"><span class="number">3.1.3 </span>Object-Oriented vs Functional</a>
                        </h3>

                        <p class="noindent">
                          As I said before, one thing that you should be aware of right off the bat is that you’re going to have to let go of your old notions of programming via object orientation.<span class="intersentencespace"></span> You’ll see what I mean by that as we look at more of the Elixir language.<span class="intersentencespace"></span> For now, let’s look at the first syntactical difference &#8211; the lack of classes.
                        </p>
                      </div>

                      <div id="uid28" data-tralics-id="uid28" class="subsection" data-number="3.1.4">
                        <h3>
                          <a href="#uid28" class="heading hyperref"><span class="number">3.1.4 </span>Modules vs Classes</a>
                        </h3>

                        <p class="noindent">
                          If you’re coming from the Ruby world or some other object-oriented paradigm like Java, you may be used to dealing with the concept of classes.<span class="intersentencespace"></span> In Elixir, there’s no such thing as a class.<span class="intersentencespace"></span> Instead Elixir gives you a module, which is a way to group functions together.
                        </p>

                        <p>
                          The other interesting implication of not having classes is that there’s no such thing as “an instance of a class”, or in this case “an instance of a module”.<span class="intersentencespace"></span> You always call functions with the following syntax of <em>ModuleName.function_name(arg1, arg2, …)</em>.
                        </p>

                        <p>
                          Below is an example of a <em>Calculator</em> module with an add function.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>defmodule Calculator do

def add(x, y) do x + y end end

                        <p>
                          In a working Elixir program, you might have the Calculator perform some work with the following code:
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Calculator.add(2,3)

=> 5

                      <div id="uid29" data-tralics-id="uid29" class="subsection" data-number="3.1.5">
                        <h3>
                          <a href="#uid29" class="heading hyperref"><span class="number">3.1.5 </span>Functions: Input X, Receive Y</a>
                        </h3>

                        <p class="noindent">
                          Now that you’ve gotten a taste of Elixir modules and functions, I want to introduce one more analogy to help you wrap your head around the concept of functional programming.<span class="intersentencespace"></span> If you’ve ever taken an algebra class, you might be used to hearing about functions such as “f of x” (denoted f(x) for short).
                        </p>

                        <p>
                          You might have seen things like <em>y = f(x) = x + 2</em> which means f(x) (or y) is the result of adding 2 to every input x.<span class="intersentencespace"></span> And that’s simply how Elixir operates &#8211; you take some data, transform it via a function, and voila, you have a new result, or a new piece of data to operate on.
                        </p>

                        <p>
                          If you haven’t taken algebra before, then you can think of it as a magician putting something into a hat (say a feather), and then pulling something else out of it, like a rabbit.<span class="intersentencespace"></span> One thing went in, and another came out.
                        </p>
                      </div>

                      <div id="uid30" data-tralics-id="uid30" class="subsection" data-number="3.1.6">
                        <h3>
                          <a href="#uid30" class="heading hyperref"><span class="number">3.1.6 </span>Goodbye Inheritance</a>
                        </h3>

                        <p class="noindent">
                          If you’re used to Ruby, you might be used to seeing inherited classes like the Dog class.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>class Mammal

def backbone? true end end class Dog < Mammal end

                        <p>
                          There’s no such thing as inheritance in Elixir.<span class="intersentencespace"></span> You just have modules that contain functions to operate on data.
                        </p>
                      </div>

                      <div id="uid31" data-tralics-id="uid31" class="subsection" data-number="3.1.7">
                        <h3>
                          <a href="#uid31" class="heading hyperref"><span class="number">3.1.7 </span>Immutability</a>
                        </h3>

                        <p class="noindent">
                          The other sticking point about Elixir that makes it different from an object-oriented language like Ruby is that data is immutable.<span class="intersentencespace"></span> In fact, hang around in the Elixir community long enough, and you’ll hear the word “immutability” thrown around a lot.
                        </p>

                        <p>
                          I already gave an explanation above, so I won’t rehash it.<span class="intersentencespace"></span> But to give it to you in the simplest terms, “data is immutable” means we never change data in memory, we only make copies of the data and transform it as necessary.<span class="intersentencespace"></span> The practical implication of this is that we don’t hold state in variables.
                        </p>
                      </div>

                      <div id="uid32" data-tralics-id="uid32" class="subsection" data-number="3.1.8">
                        <h3>
                          <a href="#uid32" class="heading hyperref"><span class="number">3.1.8 </span>How do you do state?</a>
                        </h3>

                        <p class="noindent">
                          This of course begs the question, then “how do you do state”?<span class="intersentencespace"></span> We’ll look at that in upcoming sections.<span class="intersentencespace"></span> For now, it’s sufficient to say that Elixir lets you hold state via a process mechanism.<span class="intersentencespace"></span> And it gives you tools like GenServer to help you do it.
                        </p>
                      </div>
                    </div>

                    <div id="cid10" data-tralics-id="cid10" class="section" data-number="3.2">
                      <h2>
                        <a href="#cid10" class="heading hyperref"><span class="number">3.2 </span>Summary</a>
                      </h2>

                      <p class="noindent">
                        It might take a little while for you to “empty your cup”, but hopefully the upcoming quizzes and projects will help you wrap your head around Elixir and functional programming concepts.
                      </p>
                    </div>

                    <div id="cha-3_footnotes">
                      <ol class="footnotes">
                        <li id="cha-3_footnote-1">
                          <a href="http://bengtwendel.com/your-teacup-is-full-empty-your-cup/" target="_blank" rel="noopener">Source: http://bengtwendel.com/your-teacup-is-full-empty-your-cup/</a> <a class="arrow" href="#cha-3_footnote-ref-1">↑</a>
                        </li>
                      </ol>

                      <p>
                        <a href='https://binarywebpark.clickfunnels.com/optinsurvey8kfrv6j4' target='_blank'><img src="http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px.png" alt="" width="800" height="800" class="alignnone size-full wp-image-1723" srcset="http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px.png 800w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-150x150.png 150w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-300x300.png 300w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-768x768.png 768w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-550x550.png 550w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-500x500.png 500w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-225x225.png 225w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-200x200.png 200w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-400x400.png 400w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-260x260.png 260w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-600x600.png 600w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-414x414.png 414w" sizes="(max-width: 800px) 100vw, 800px" /></a>
                      </p>
                    </div>

                    <div id="cha-chapter3" data-tralics-id="cid11" class="chapter" data-number="4">
                      <h1>
                        <a href="#cha-chapter3" class="heading hyperref"><span class="number">Chapter 4 </span>The Enum Module: The Answer To Ruby’s Enumerable</a>
                      </h1>
                    </div>

                    <div id="cid12" data-tralics-id="cid12" class="section" data-number="4.1">
                      <h2>
                        <a href="#cid12" class="heading hyperref"><span class="number">4.1 </span>Everyone Loves the Count</a>
                      </h2>

                      <p class="noindent">
                        When I was a little boy, I used to watch Sesame Street.<span class="intersentencespace"></span> The show had this character called Count von Count, or simply, <em>The Count</em>.
                      </p>

                      <p>
                        His job on the show was to teach kids about simple mathematical concepts like counting.<span class="intersentencespace"></span> Watching him made counting and other mathematical concepts entertaining and fun to apply.
                      </p>

                      <div id="uid33" data-tralics-id="uid33" class="subsection" data-number="4.1.1">
                        <h3>
                          <a href="#uid33" class="heading hyperref"><span class="number">4.1.1 </span>But then I grew up and discovered the Enumerable module…</a>
                        </h3>

                        <p class="noindent">
                          As a self-taught web programmer, my first language was Ruby, via learning Ruby on Rails.<span class="intersentencespace"></span> One thing that was new to me was the the Enumerable module and its methods.<span class="intersentencespace"></span> As I got used to it, I found the Enumerable module quite beautiful as it enabled me to easily and elegantly operate on array collections.<span class="intersentencespace"></span> JavaScript has similar methods and I’d be willing to be other object-oriented languages do as well.
                        </p>

                        <p>
                          In fact, if type “enumerable” into Google, I get the definition “able to be counted by one-to-one correspondence with the set of all positive integers.”
                        </p>

                        <p>
                          In fact, Ruby’s Enumerable module does feel like it’s designed to operate on a list of integers (or other “objects”).<span class="intersentencespace"></span> It became such a part of my toolset what I was hoping Elixir had one…
                        </p>
                      </div>
                    </div>

                    <div id="sec-enum_module" data-tralics-id="cid13" class="section" data-number="4.2">
                      <h2>
                        <a href="#sec-enum_module" class="heading hyperref"><span class="number">4.2 </span>Introducing Enum…</a>
                      </h2>

                      <p class="noindent">
                        Fortunately, Jose Valim, the creator of Elixir, was formerly a Ruby language programmer.<span class="intersentencespace"></span> So I’m betting he too appreciated the Enumerable module.<span class="intersentencespace"></span> And hence, we have the Enum module in Elixir.
                      </p>

                      <p>
                        Like the Enumerable module in Ruby, Elixir also provides us with the Enum module to work with collections.<span class="intersentencespace"></span> Typically, you’ll find yourself operating on lists and maps.
                      </p>

                      <p>
                        Lists look a lot like arrays in Ruby, but we’ll stick with the Elixir way of calling them lists.
                      </p>
                    </div>

                    <div id="cid14" data-tralics-id="cid14" class="section" data-number="4.3">
                      <h2>
                        <a href="#cid14" class="heading hyperref"><span class="number">4.3 </span>Useful Enum Module Methods</a>
                      </h2>

                      <p class="noindent">
                        Now let’s go over some useful Enum module methods.<span class="intersentencespace"></span> These are methods I find myself using over and over again in real world applications.
                      </p>

                      <div id="uid34" data-tralics-id="uid34" class="subsection" data-number="4.3.1">
                        <h3>
                          <a href="#uid34" class="heading hyperref"><span class="number">4.3.1 </span>Enum#at</a>
                        </h3>

                        <p class="noindent">
                          Let’s suppose we have the following list of integers bound to m.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = [2, 1, 4]
                        <p>
                          What happens if we wanted to get the second element?<span class="intersentencespace"></span> In Ruby, you might do something like <code>m[1]</code>.<span class="intersentencespace"></span> You’ll find if you try that in Elixir you’ll get an error.<span class="intersentencespace"></span> Instead, you can use the at method of the Enum module as follows.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.at(m, 1)

=> 1

                      <div id="uid35" data-tralics-id="uid35" class="subsection" data-number="4.3.2">
                        <h3>
                          <a href="#uid35" class="heading hyperref"><span class="number">4.3.2 </span>Enum#reduce</a>
                        </h3>

                        <p class="noindent">
                          If you’re used to Ruby’s inject operator, you’ve probably seen things like:
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [1, 2, 3]

a.inject { |sum, x| sum + x }

=> 6

                        <p>
                          The reduce method of the Enum module operates much the same way.<span class="intersentencespace"></span> Like all things in Elixir the major syntacitcal difference is that you call it using the module name follwed by the method name as follows:
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.reduce([1, 2, 3], fn(x, accumulator) -> x + accumulator end)

=> 6 is the sum of 1, 2, and 3

                        <p>
                          Note that just like in Ruby’s inject method, the Enum#reduce method has an accumulator to hold the results of your computations.
                        </p>
                      </div>

                      <div id="uid36" data-tralics-id="uid36" class="subsection" data-number="4.3.3">
                        <h3>
                          <a href="#uid36" class="heading hyperref"><span class="number">4.3.3 </span>Enum#map</a>
                        </h3>

                        <p class="noindent">
                          Like Ruby, Elixir also gives you a map operator.
                        </p>

                        <p>
                          In Ruby:
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [1, 2, 3]

a.map { |x| x * 2}

=> [2, 4, 6]

                        <p>
                          In Elixir:
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.map([1, 2, 3], fn(x) -> x * 2 end)

=> [2, 4, 6]

                      <div id="uid37" data-tralics-id="uid37" class="subsection" data-number="4.3.4">
                        <h3>
                          <a href="#uid37" class="heading hyperref"><span class="number">4.3.4 </span>Enum#filter</a>
                        </h3>

                        <p class="noindent">
                          Ruby gives you a handy select method to “filter” elements you want from an array.<span class="intersentencespace"></span> Below we select all elements from the array for which the condition holds true.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>[1, 2, 3].select { |x| x%2 == 0}

=> [2]

                        <p>
                          The Enum#filter method operates much the same way.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)

=> [2]

                      <div id="uid38" data-tralics-id="uid38" class="subsection" data-number="4.3.5">
                        <h3>
                          <a href="#uid38" class="heading hyperref"><span class="number">4.3.5 </span>Enum#reject</a>
                        </h3>

                        <p class="noindent">
                          Ruby’s converse of the select method is the reject method.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>[1, 2, 3].reject { |x| x%2 == 0}

=> [1, 3]

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)

=> [1, 3]

                      <div id="uid39" data-tralics-id="uid39" class="subsection" data-number="4.3.6">
                        <h3>
                          <a href="#uid39" class="heading hyperref"><span class="number">4.3.6 </span>Enum#all?</a>
                        </h3>

                        <p class="noindent">
                          Ruby also has an <em>all?</em><span class="intersentencespace"></span> method which is extremely similar to Elixir’s.<span class="intersentencespace"></span> Or perhaps I should say it’s the other way around.
                        </p>

                        <p>
                          In any case, the <em>all?</em><span class="intersentencespace"></span> method returns true if all the elements meet the condition.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>[1, 2, 3].all? { |x| x%2==0 }

=> false

                        <p>
                          Hopefully by now you’re seeing a common pattern.<span class="intersentencespace"></span> There are parts of Elixir’s syntax that borrow beautifully from Ruby (or should I say shamelessly copy?)
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.all?([1, 2, 3], fn(x) -> rem(x,2) == 0 end)

=> false

                      <div id="uid40" data-tralics-id="uid40" class="subsection" data-number="4.3.7">
                        <h3>
                          <a href="#uid40" class="heading hyperref"><span class="number">4.3.7 </span>Enum#any?</a>
                        </h3>

                        <p class="noindent">
                          Ruby also has an <em>any?</em><span class="intersentencespace"></span> method to check if any element in a collection meets a particular condition.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>[1, 2, 3].any? { |x| x%2==0 }

=> true

                        <p>
                          Elixir also has an <em>any?</em><span class="intersentencespace"></span> method.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.any?([1, 2, 3], fn(x) -> rem(x,2) == 0 end)

=> true

                      <div id="uid41" data-tralics-id="uid41" class="subsection" data-number="4.3.8">
                        <h3>
                          <a href="#uid41" class="heading hyperref"><span class="number">4.3.8 </span>Enum#to_list with a range</a>
                        </h3>

                        <p class="noindent">
                          Sometimes you want to generate a long list of numbers but you don’t want to type it all out.<span class="intersentencespace"></span> The solution is to pass a range into Enum’s <em>to_list</em> method and let it do the work for you.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.to_list(1..3)

=> [1, 2, 3]

                      <div id="uid42" data-tralics-id="uid42" class="subsection" data-number="4.3.9">
                        <h3>
                          <a href="#uid42" class="heading hyperref"><span class="number">4.3.9 </span>Enum#count</a>
                        </h3>

                        <p class="noindent">
                          Sometimes you just want to know the length of a list.<span class="intersentencespace"></span> The <em>count</em> method can easily do that for you.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.count [1, 2, 3]

=> 3

                    <div id="cid15" data-tralics-id="cid15" class="section" data-number="4.4">
                      <h2>
                        <a href="#cid15" class="heading hyperref"><span class="number">4.4 </span>Summary</a>
                      </h2>

                      <p class="noindent">
                        Like Sesame Street’s, The Count, the Enum module makes learning fun.<span class="intersentencespace"></span> The Enum module gives you quite a few useful methods for operating on data.<span class="intersentencespace"></span> I encourage you to read the documentation and discover even more methods.<span class="intersentencespace"></span> An upcoming quiz will ask you to make use of Enum’s methods, so stay tuned!
                      </p>
                    </div>

                    <div id="cha-chapter4" data-tralics-id="cid16" class="chapter" data-number="5">
                      <h1>
                        <a href="#cha-chapter4" class="heading hyperref"><span class="number">Chapter 5 </span>The List Module</a>
                      </h1>
                    </div>

                    <div id="cid17" data-tralics-id="cid17" class="section" data-number="5.1">
                      <h2>
                        <a href="#cid17" class="heading hyperref"><span class="number">5.1 </span>The Linked List Data Structure and the CSV Reporter</a>
                      </h2>

                      <p class="noindent">
                        I did study Computer Science in university, and one thing they covered was the linked list data structure.<span class="intersentencespace"></span> In Ruby (and other object-oriented languages), you basically get these for free through arrays.
                      </p>

                      <p>
                        Instead of arrays, Elixir has a concept called “lists”.<span class="intersentencespace"></span> They look very much like arrays and behave much the same way.<span class="intersentencespace"></span> They are an Elixir version of linked lists.
                      </p>
                    </div>

                    <div id="cid18" data-tralics-id="cid18" class="section" data-number="5.2">
                      <h2>
                        <a href="#cid18" class="heading hyperref"><span class="number">5.2 </span>Making a YouTube CSV Reporter</a>
                      </h2>

                      <p class="noindent">
                        While building my first simple production application, I built an Elixir application that pulled down data from YouTube and turned it into a CSV (comma-separate value) report.<span class="intersentencespace"></span> It pulled down publicly available metrics and emailed them to a business unit that needed them for reporting purposes.
                      </p>

                      <p>
                        As I built this application, I found myself operating on lists of data in Elixir.<span class="intersentencespace"></span> In fact, I’d say all my real world application usage of Elixir involved Lists in some way.<span class="intersentencespace"></span> So it’s definitely worth familiarizing yourself with the List module in Elixir.
                      </p>
                    </div>

                    <div id="sec-list_module" data-tralics-id="cid19" class="section" data-number="5.3">
                      <h2>
                        <a href="#sec-list_module" class="heading hyperref"><span class="number">5.3 </span>Useful List Module Methods</a>
                      </h2>

                      <p class="noindent">
                        Like the Array module in Ruby, Elixir also provides us with a module to work with lists.<span class="intersentencespace"></span> Typically, you’ll find yourself operating on lists and maps.
                      </p>

                      <p>
                        Lists look a lot like arrays in Ruby, but we’ll stick with the Elixir way of calling them lists.
                      </p>

                      <div id="uid43" data-tralics-id="uid43" class="subsection" data-number="5.3.1">
                        <h3>
                          <a href="#uid43" class="heading hyperref"><span class="number">5.3.1 </span>List.first</a>
                        </h3>

                        <p class="noindent">
                          Here is the Ruby syntax for calling first on an array.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [1, 2, 3]

a.first

=> 1

                        <p>
                          And here is the Elixir syntax for calling first on a list.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [1, 2, 3]

List.first(a)

=> 1

                      <div id="uid44" data-tralics-id="uid44" class="subsection" data-number="5.3.2">
                        <h3>
                          <a href="#uid44" class="heading hyperref"><span class="number">5.3.2 </span>List.last</a>
                        </h3>

                        <p class="noindent">
                          Here is the Ruby syntax for calling last on an array.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [1, 2, 3]

a.last

=> 3

                        <p>
                          And here is the Elixir syntax for calling last on a list.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [1, 2, 3]

List.last(a)

=> 1

                      <div id="uid45" data-tralics-id="uid45" class="subsection" data-number="5.3.3">
                        <h3>
                          <a href="#uid45" class="heading hyperref"><span class="number">5.3.3 </span>List.flatten</a>
                        </h3>

                        <p class="noindent">
                          Ruby gives you a flatten method for arrays as follows.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [[1,2], [[3], 4]]

a.flatten

=> [1, 2, 3, 4]

                        <p>
                          And so does Elixir.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [[1,2], [[3], 4]]

List.flatten(a)

=> [1, 2, 3, 4]

                      <div id="uid46" data-tralics-id="uid46" class="subsection" data-number="5.3.4">
                        <h3>
                          <a href="#uid46" class="heading hyperref"><span class="number">5.3.4 </span>List.foldl</a>
                        </h3>

                        <p class="noindent">
                          Off the top of my head, I don’t know of a Ruby equivalent for Elixir’s <em>foldl</em> method.
                        </p>

                        <p>
                          But the <em>foldl</em> method uses a function to reduce the list from the left.<span class="intersentencespace"></span> Below is a code snippet with an explanation of how the list is being folded.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [3, 2, 1]

List.foldl(a, 0, fn(elem, accumulator) -> elem - accumulator end)

=> 2

because 3-0 = 3, 2 - 3 = -1, and 1 - (-1) = 2

                      <div id="uid47" data-tralics-id="uid47" class="subsection" data-number="5.3.5">
                        <h3>
                          <a href="#uid47" class="heading hyperref"><span class="number">5.3.5 </span>List.insert_at</a>
                        </h3>

                        <p class="noindent">
                          Elixir’s <em>List#insert_at</em> function is probably closest to Ruby’s <em>Array#insert</em> function.
                        </p>

                        <p>
                          Here is how you insert into an array at a particular index value.<span class="intersentencespace"></span> We insert the value 5 at index 1.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [1, 2, 3]

a.insert(1, 5)

=> [1, 5, 2, 3]

                        <p>
                          Here is the Elixir equivalent.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [1, 2, 3]

List.insert_at(a, 1, 5)

=> [1, 5, 2, 3]

                      <div id="uid48" data-tralics-id="uid48" class="subsection" data-number="5.3.6">
                        <h3>
                          <a href="#uid48" class="heading hyperref"><span class="number">5.3.6 </span>List.delete_at</a>
                        </h3>

                        <p class="noindent">
                          When deleting an element out of a list in Elixir, you simply specify the index number at which you wish to delete the element.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [1, 5, 2, 3]

List.delete_at(a, 1)

=> [1, 5, 2, 3]

                      <div id="uid49" data-tralics-id="uid49" class="subsection" data-number="5.3.7">
                        <h3>
                          <a href="#uid49" class="heading hyperref"><span class="number">5.3.7 </span>++ and - -</a>
                        </h3>

                        <p class="noindent">
                          You can add elements to a list in Elixir with the <em>++</em> operator and remove them with the <em>- -</em> operator.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>[1, 2] ++ [-1, 5]

=> [1, 2, -1, 5]

t = [1, 2, -1, 5] t — [1]

=> [2, -1, 5]

                    <div id="cid20" data-tralics-id="cid20" class="section" data-number="5.4">
                      <h2>
                        <a href="#cid20" class="heading hyperref"><span class="number">5.4 </span>Summary</a>
                      </h2>

                      <p class="noindent">
                        Lists are one of the most common data structures used in day to day Elixir development in my experience.<span class="intersentencespace"></span> It’s worth knowing the methods in that module as you will be using them frequently.
                      </p>
                    </div>

                    <div id="cha-chapter5" data-tralics-id="cid21" class="chapter" data-number="6">
                      <h1>
                        <a href="#cha-chapter5" class="heading hyperref"><span class="number">Chapter 6 </span>The Map Module</a>
                      </h1>
                    </div>

                    <div id="cid22" data-tralics-id="cid22" class="section" data-number="6.1">
                      <h2>
                        <a href="#cid22" class="heading hyperref"><span class="number">6.1 </span>The Dictionary</a>
                      </h2>

                      <p class="noindent">
                        If you’ve ever used Webster’s Dictionary, you know you look up a word, say “aardvark”, and flip through the pages to locate the definition.<span class="intersentencespace"></span> If you think of “aardvark” as a key of sorts, and then its corresponding definition as a “value”, you’ll have an analogy to the dictionary abstract data type.
                      </p>

                      <p>
                        Basically, you use a key to access a value.<span class="intersentencespace"></span> The first important property of a dictionary are that the keys are hashabale and equally comparable, which is often why keys are letters or numbers.<span class="intersentencespace"></span> The second important property is that the entries appear in no particular order (which is a contrast to Webster’s Dictionary).<sup id="cha-6_footnote-ref-1" class="footnote"><a href="#cha-6_footnote-1">1</a></sup>
                      </p>

                      <p>
                        The Ruby language has an implementation of the dictionary data type called a Hash.<span class="intersentencespace"></span> So do other object-oriented languages like Java.
                      </p>
                    </div>

                    <div id="cid23" data-tralics-id="cid23" class="section" data-number="6.2">
                      <h2>
                        <a href="#cid23" class="heading hyperref"><span class="number">6.2 </span>But what about Elixir?</a>
                      </h2>

                      <p class="noindent">
                        Elixir has an implementation called a map.<span class="intersentencespace"></span> In fact, when I was building a reporting tool that emailed comma-separated value text files, I used the Map module quite a bit.<span class="intersentencespace"></span> As you work with Elixir, you’ll likely find that you use the Map module quite a bit as you transform and iterate over your data.
                      </p>

                      <p>
                        So let’s dive in to some useful map methods.
                      </p>
                    </div>

                    <div id="sec-map_module" data-tralics-id="cid24" class="section" data-number="6.3">
                      <h2>
                        <a href="#sec-map_module" class="heading hyperref"><span class="number">6.3 </span>Useful Map Module Methods</a>
                      </h2>

                      <p class="noindent">
                        Besides lists, the other data structure you’ll encounter frequently in Elixir are maps.<span class="intersentencespace"></span> I have found myself using them in everything I do,
                      </p>

                      <div id="uid51" data-tralics-id="uid51" class="subsection" data-number="6.3.1">
                        <h3>
                          <a href="#uid51" class="heading hyperref"><span class="number">6.3.1 </span>Map.get</a>
                        </h3>

                        <p class="noindent">
                          So Map’s <em>get</em> method lets you fetch a value by key.<span class="intersentencespace"></span> It’s very similar to the <em>fetch</em> method for a hash in Ruby.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, "c" => 3, :d => 4}

Map.get(m, :b)

=> 2

Map.get(m, :c)

=> nil

Map.get(m, “c”)

=> 3

                        <p>
                          You’ll notice from the above code, you have to be very specific about which key you use to fetch a value.
                        </p>
                      </div>

                      <div id="uid52" data-tralics-id="uid52" class="subsection" data-number="6.3.2">
                        <h3>
                          <a href="#uid52" class="heading hyperref"><span class="number">6.3.2 </span>Map.put</a>
                        </h3>

                        <p class="noindent">
                          Map’s <em>put</em> method is for putting a value associated with a key in a map.<span class="intersentencespace"></span> It can be used for adding new key and value pairs or updating old ones.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, :c => 3}

Map.put(m, :c, 5)

=> %{b: 2, c: 5}

                      <div id="uid53" data-tralics-id="uid53" class="subsection" data-number="6.3.3">
                        <h3>
                          <a href="#uid53" class="heading hyperref"><span class="number">6.3.3 </span>Elixir’s built-in syntax for updating maps</a>
                        </h3>

                        <p class="noindent">
                          One cool trick I’ve learned from reading <a href="https://dockyard.com/blog/2016/03/07/til-elixir-maps-have-built-in-syntax-for-updating" target="_blank" rel="noopener">this blog post</a> is how to do updating one or more map key values using a special syntax
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, :c => 3}

%{m | :b => 4, :c => 5}

=> %{b: 4, c: 5}

                      <div id="uid54" data-tralics-id="uid54" class="subsection" data-number="6.3.4">
                        <h3>
                          <a href="#uid54" class="heading hyperref"><span class="number">6.3.4 </span>Map.has_key?</a>
                        </h3>

                        <p class="noindent">
                          Similar to a Ruby hash, Elixir gives you the ability to check if a given key is in a map.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, :c => 3}

Map.has_key?(m, :b)

=> true

                      <div id="uid55" data-tralics-id="uid55" class="subsection" data-number="6.3.5">
                        <h3>
                          <a href="#uid55" class="heading hyperref"><span class="number">6.3.5 </span>Map.keys</a>
                        </h3>

                        <p class="noindent">
                          Using Map’s <em>keys</em> function, you can get a list of keys only.<span class="intersentencespace"></span> This is analagous to Ruby’s <em>keys</em> function for Hash.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, :c => 3}

Map.keys(m)

=> [:b, :c]

                      <div id="uid56" data-tralics-id="uid56" class="subsection" data-number="6.3.6">
                        <h3>
                          <a href="#uid56" class="heading hyperref"><span class="number">6.3.6 </span>Map.values</a>
                        </h3>

                        <p class="noindent">
                          Using Map’s <em>values</em> function, you can get a list of values only.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, :c => 3}

Map.values(m)

=> [2, 3]

                      <div id="uid57" data-tralics-id="uid57" class="subsection" data-number="6.3.7">
                        <h3>
                          <a href="#uid57" class="heading hyperref"><span class="number">6.3.7 </span>Map.replace</a>
                        </h3>

                        <p class="noindent">
                          Map’s <em>replace</em> is handy in that it will alter the value associated with a key, but only if that key exists.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, :c => 3}

Map.replace(m, :b , 2)

=> %{b: 4, c: 3}

                      <div id="uid58" data-tralics-id="uid58" class="subsection" data-number="6.3.8">
                        <h3>
                          <a href="#uid58" class="heading hyperref"><span class="number">6.3.8 </span>Map.merge</a>
                        </h3>

                        <p class="noindent">
                          Map’s <em>merge</em> is another handy data transformation function I often find myself using to merge 2 maps together.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, :c => 3}

Map.merge(m, %{d: 5})

=> %{b: 2, c: 3, d: 5}

                      <div id="uid59" data-tralics-id="uid59" class="subsection" data-number="6.3.9">
                        <h3>
                          <a href="#uid59" class="heading hyperref"><span class="number">6.3.9 </span>Map.drop</a>
                        </h3>

                        <p class="noindent">
                          Map’s <em>drop</em> is good for removing keys from the list.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, :c => 3}

Map.drop(m, [:c])

=> %{b: 2}

                      <div id="uid60" data-tralics-id="uid60" class="subsection" data-number="6.3.10">
                        <h3>
                          <a href="#uid60" class="heading hyperref"><span class="number">6.3.10 </span>Map.to_list</a>
                        </h3>

                        <p class="noindent">
                          Interestingly enough, I recently found out you could convert maps to a list of tuples.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{:b => 2, :c => 3}

t = Map.to_list(m)

=> [b: 2, c: 3]

List.first t

=> {:b, 2}

                      <div id="uid61" data-tralics-id="uid61" class="subsection" data-number="6.3.11">
                        <h3>
                          <a href="#uid61" class="heading hyperref"><span class="number">6.3.11 </span>Map.update</a>
                        </h3>

                        <p class="noindent">
                          I haven’t used Map’s <em>update</em> too much, but it’s pretty handy for updating key values in a map.<span class="intersentencespace"></span> In the below example, code I used an initial value of “-1”, which is what the value of “a” would have been if it had not already existed in the map.<span class="intersentencespace"></span> Instead, the value of a is set to “1 times 3”, which is 3.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>m = %{"a" => 1, "b" => 2}

Map.update(m, “a”, -1, &(&1 * 3))

=> %{“a” => 3, “b” => 2}

                      <div id="uid62" data-tralics-id="uid62" class="subsection" data-number="6.3.12">
                        <h3>
                          <a href="#uid62" class="heading hyperref"><span class="number">6.3.12 </span>A word on nested maps</a>
                        </h3>

                        <p class="noindent">
                          One thing I found that was hard to deal with was when I wanted to drop keys out of nested maps.<span class="intersentencespace"></span> To that end, I built a <a href="https://github.com/treble37/nested_filter" target="_blank" rel="noopener">hex package called nested_filter</a> to handle this.<span class="intersentencespace"></span> It’s a bit complicated at this point, but someone was kind enough to review it and if you go through the commit history you can see how it evolved.
                        </p>

                        <p>
                          We’ll probably come back to this later when we discuss anonymous functions, but I wanted it to mention it now in case you wanted to take a look.
                        </p>
                      </div>
                    </div>

                    <div id="cid25" data-tralics-id="cid25" class="section" data-number="6.4">
                      <h2>
                        <a href="#cid25" class="heading hyperref"><span class="number">6.4 </span>Summary</a>
                      </h2>

                      <p class="noindent">
                        The Map module is something you’ll use over and over again.<span class="intersentencespace"></span> It’s something I used in my first Elixir application for CSV reports and it’s something I still use in my production applications today.
                      </p>

                      <div id="uid63" data-tralics-id="uid63" class="subsection" data-number="6.4.1">
                        <h3>
                          <a href="#uid63" class="heading hyperref"><span class="number">6.4.1 </span>Footnotes</a>
                        </h3>
                      </div>
                    </div>

                    <div id="cha-6_footnotes">
                      <ol class="footnotes">
                        <li id="cha-6_footnote-1">
                          <a href="https://softwareengineering.stackexchange.com/questions/30908/difference-between-hash-and-dictionary" target="_blank" rel="noopener">Source: https://softwareengineering.stackexchange.com/questions/30908/difference-between-hash-and-dictionary</a> <a class="arrow" href="#cha-6_footnote-ref-1">↑</a>
                        </li>
                      </ol>
                    </div>

                    <div id="cha-chapter7" data-tralics-id="cid26" class="chapter" data-number="7">
                      <h1>
                        <a href="#cha-chapter7" class="heading hyperref"><span class="number">Chapter 7 </span>Conditionals in Elixir</a>
                      </h1>
                    </div>

                    <div id="sec-map_module" data-tralics-id="cid27" class="section" data-number="7.1">
                      <h2>
                        <a href="#sec-map_module" class="heading hyperref"><span class="number">7.1 </span>Conditional Control Flow Structures</a>
                      </h2>

                      <div id="uid64" data-tralics-id="uid64" class="subsection" data-number="7.1.1">
                        <h3>
                          <a href="#uid64" class="heading hyperref"><span class="number">7.1.1 </span>My Overreliance on Cond</a>
                        </h3>

                        <p class="noindent">
                          When I first started with Elixir I tended to rely on conditionals much more than I would care to admit.<span class="intersentencespace"></span> This is because I wasn’t quite fluent with a concept called pattern matching, which is something we’ll talk about in upcoming course modules.
                        </p>

                        <p>
                          I tended to do things like:
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>defmodule NestedFilter do

def dropbykey(map, filterkeys) do cond do isnestedmap?(map) -> newmap = map |> Enum.reduce(%{}, fn({key, val}, acc) -> Map.put(acc, key, dropbykey(val, filterkeys)) end) Map.drop(newmap, filterkeys) ismap(map) -> Map.drop(map, filter_keys) true -> map end end end

                        <p>
                          Today I would cringe at that kind of code.<span class="intersentencespace"></span> A better improvement would have been to use a case statement (and an even better one would be the use of pattern matching).<span class="intersentencespace"></span> And that leads us to the topic of conditionals.<span class="intersentencespace"></span> We’re going to talk about cond, case, and if.
                        </p>
                      </div>

                      <div id="uid65" data-tralics-id="uid65" class="subsection" data-number="7.1.2">
                        <h3>
                          <a href="#uid65" class="heading hyperref"><span class="number">7.1.2 </span>Cond</a>
                        </h3>

                        <p class="noindent">
                          Coming from Ruby, <code>cond</code> reminds me of the <code>if/elsif/end</code> structure in Ruby.<span class="intersentencespace"></span> In other languages it’s equivalent to an if/else if type of control flow.
                        </p>

                        <p>
                          Its use case is to match on conditions.<span class="intersentencespace"></span> In the example below, you can see you hit the “catch all” true condition, which is like hitting the “else” portion of an if/else conditional flow in Ruby.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>defmodule Hello do

def hello(msg) do cond do msg == “world” -> “hello world” msg == “no” -> “heck no” true -> “you hit the catch all” end end end

=> “you hit the catch all”

                      <div id="uid66" data-tralics-id="uid66" class="subsection" data-number="7.1.3">
                        <h3>
                          <a href="#uid66" class="heading hyperref"><span class="number">7.1.3 </span>Case</a>
                        </h3>

                        <p class="noindent">
                          In production ready code, I’ve seen the case conditional used quite a bit, especially when pattern matching against success and error tuples.<span class="intersentencespace"></span> Below is an example snippet in the context of a Phoenix controller.<span class="intersentencespace"></span> The hypothetical “DoSomething” module does something with the incoming <code>params</code> map and then the <code>with_params</code> method returns a success or error tuple.
                        </p>

                        <p>
                          From there, we let the phoenix controller decide what to render.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>defmodule App.YourController do

def show(conn, params = %{id: id}) do case DoSomething.withparams(params) do {:ok, message} -> conn |> put_status(:ok) |> render(“show.json”, message: message) {:error, *} -> conn |> putstatus(:unprocessable_entity) |> render(“error.json”, message: “unprocessable entity”)

                        <p>
                          The underscore <code>_</code> in the case statement acts as a catchall, much like the <code>true</code> in the cond statement.
                        </p>
                      </div>

                      <div id="uid67" data-tralics-id="uid67" class="subsection" data-number="7.1.4">
                        <h3>
                          <a href="#uid67" class="heading hyperref"><span class="number">7.1.4 </span>If</a>
                        </h3>

                        <p class="noindent">
                          The interesting thing to note about Elixir’s <code>if</code> statement is that unlike Ruby, there’s no concept of <code>elsif</code>.<span class="intersentencespace"></span> So you won’t run into a lot of nested if statements (hopefully) unlike in some of the Ruby startup code bases I’ve seen.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>t = [1, 2, 3]

if is_list(t) do IO.inspect “it’s a list!” else IO.inspect “it’s NOT a list!” end

=> “it’s a list!”

                        <p>
                          You can do nested if statements, but it’s ugly and I’ve never seen it any good codebase.<span class="intersentencespace"></span> So please do avoid it, although I will show it to you here for completeness sake.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>t = 1

if islist(t) do IO.inspect “it’s a list!” else if isinteger(t) do IO.inspect “it’s an int!” else IO.inspect “it’s not an int!” end IO.inspect “it’s NOT a list!” end

=> “it’s an int!”

=> “it’s NOT a list!”

                      <div id="uid68" data-tralics-id="uid68" class="subsection" data-number="7.1.5">
                        <h3>
                          <a href="#uid68" class="heading hyperref"><span class="number">7.1.5 </span>Unless</a>
                        </h3>

                        <p class="noindent">
                          Elixir’s <code>unless</code> statement follows the same pattern as its <code>if</code> statement.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>t = 1

unless is_list(t) do IO.inspect “it’s NOT a list!” else IO.inspect “it’s a list!” end

=> “it’s NOT a list!”

                    <div id="cid28" data-tralics-id="cid28" class="section" data-number="7.2">
                      <h2>
                        <a href="#cid28" class="heading hyperref"><span class="number">7.2 </span>Summary</a>
                      </h2>

                      <p class="noindent">
                        As a general rule of thumb, a case statement is more idiomatic than cond, but cond has its uses.<span class="intersentencespace"></span> It’s rare to see if statements in Elixir, although it does happen.
                      </p>
                    </div>

                    <p>
                      <a href='https://binarywebpark.clickfunnels.com/optinsurvey8kfrv6j4' target='_blank'><img src="http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px.png" alt="" width="800" height="800" class="alignnone size-full wp-image-1723" srcset="http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px.png 800w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-150x150.png 150w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-300x300.png 300w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-768x768.png 768w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-550x550.png 550w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-500x500.png 500w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-225x225.png 225w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-200x200.png 200w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-400x400.png 400w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-260x260.png 260w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-600x600.png 600w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-414x414.png 414w" sizes="(max-width: 800px) 100vw, 800px" /></a>
                    </p>

                    <div id="cha-chapter8" data-tralics-id="cid29" class="chapter" data-number="8">
                      <h1>
                        <a href="#cha-chapter8" class="heading hyperref"><span class="number">Chapter 8 </span>Handy Keywords For Working With Modules and Anonymous Functions in Elixir</a>
                      </h1>
                    </div>

                    <div id="cid30" data-tralics-id="cid30" class="section" data-number="8.1">
                      <h2>
                        <a href="#cid30" class="heading hyperref"><span class="number">8.1 </span>The 2 Hardest Problems in Computer Science</a>
                      </h2>

                      <blockquote class="quotation">
                        <p class="quote noindent">
                          There are only two hard things in Computer Science: cache invalidation and naming things.<span class="intersentencespace"></span> – Phil Karlton
                        </p>
                      </blockquote>

                      <p>
                        So the quote from Phil Karlton I pulled from Martin Fowler’s website.<sup id="cha-8_footnote-ref-1" class="footnote"><a href="#cha-8_footnote-1">1</a></sup>
                      </p>

                      <p>
                        And the longer I kept programming, the more I realized that Phil was right.<span class="intersentencespace"></span> Naming things - whether it be variables, classes, or files - is really hard.<span class="intersentencespace"></span> I can recall in my own object-oriented programming, how taxing it could be trying to name classes and methods in accordance with the problem domain I was looking at.
                      </p>

                      <p>
                        Unfortunately, functional programming with Elixir can’t solve this problem.<span class="intersentencespace"></span> However, there are tricks Elixir gives you to save you from typing your module names over and over.
                      </p>

                      <p>
                        When working with the Elixir frameworks such as Phoenix, you’ll find these tricks useful especially when dealing with the namespacing of modules.
                      </p>

                      <p>
                        In this section, we’re going to talk about handy keywords when working with Modules as well as Anonymous Functions in Elixir.
                      </p>
                    </div>

                    <div id="sec-alias" data-tralics-id="cid31" class="section" data-number="8.2">
                      <h2>
                        <a href="#sec-alias" class="heading hyperref"><span class="number">8.2 </span>Alias and Import</a>
                      </h2>

                      <p class="noindent">
                        Alias and import are two of the most common features of Elixir you’ll most likely be using when you first start using Elixir, especially if you’re using it in a web application (at least in my experience).
                      </p>

                      <div id="uid70" data-tralics-id="uid70" class="subsection" data-number="8.2.1">
                        <h3>
                          <a href="#uid70" class="heading hyperref"><span class="number">8.2.1 </span>Alias</a>
                        </h3>

                        <p class="noindent">
                          I think of the <code>alias</code> command as a shortcut to save you from typing.<span class="intersentencespace"></span> In actuality, you can do more with it.
                        </p>

                        <p>
                          For example, suppose you have the following module(s) defined.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>defmodule Project.Calculator.Adder do

def add(a,b), do: a + b def add(a, b, c), do: a + b + c end defmodule Project.Machine do alias Project.Calculator.Adder

we can call Adder.add thanks to alias

def addtwo(a, b), do: Adder.add(a, b) end defmodule Project.Machine2 do alias Project.Calculator.Adder, as: C def addtwo(a, b), do: C.add(a, b) end

                        <p>
                          We could have also aliased <code>Project.Calculator.Adder</code> as something else entirely with the <code>as</code> option as shown in the <code>Project.Machine2</code> module.
                        </p>

                        <p>
                          The other thing you can do is alias more than one module in the same line.<span class="intersentencespace"></span> In the below example, I am aliasing the Project.Calculator.Arithmetic modules and the Project.Calculator.Subtracter modules in one line.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>defmodule Project.Calculator.Arithmetic do

def hello, do: “hello” end defmodule Project.Calculator.Subtracter do def subtract(a, b), do: a - b end defmodule Project.Calculator.Adder do alias Project.Calculator.{Arithmetic, Subtracter} end

                        <p>
                          Try the source code for yourself by copying and pasting it in the iex shell.
                        </p>
                      </div>

                      <div id="uid71" data-tralics-id="uid71" class="subsection" data-number="8.2.2">
                        <h3>
                          <a href="#uid71" class="heading hyperref"><span class="number">8.2.2 </span>Import</a>
                        </h3>

                        <p class="noindent">
                          I think of import as a way to easily use functions from other modules without having to type out any part of the module name (unlike alias).
                        </p>

                        <p>
                          Here’s how that would look with our Calculator example.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>defmodule Project.Calculator.Adder do

def add(a,b), do: a + b def add(a, b, c), do: a + b + c end defmodule Project.Machine do import Project.Calculator.Adder

import Project.Calculator.Adder, only: [add: 2, add: 3]

we can call Adder.add as add thanks to import

def addtwo(a, b), do: add(a, b) def addthree(a, b, c), do: add(a, b, c) end

                        <p>
                          Interestingly enough, I recently learned that import has an <code>only</code> option to let you only import macros or functions.<span class="intersentencespace"></span> You can also specify specific functions that get called as well.<span class="intersentencespace"></span> You’ll notice the numbers 2 and 3 in the code above.<span class="intersentencespace"></span> This tells Elixir to only import the function that takes 2 arguments or 3 arguments, respectively.
                        </p>

                        <p>
                          You can see this in the commented line in the previous code block example with <code>Project.Machine</code>.
                        </p>
                      </div>
                    </div>

                    <div id="sec-module_attributes" data-tralics-id="cid32" class="section" data-number="8.3">
                      <h2>
                        <a href="#sec-module_attributes" class="heading hyperref"><span class="number">8.3 </span>Module Attributes</a>
                      </h2>

                      <p class="noindent">
                        If you’re used to constants in Ruby, you might be wondering what is the best way to handle those in Elixir.<span class="intersentencespace"></span> So far, I’ve found 2 good ways, one is through using private functions (<code>defp my_function, do: "private_constant"</code>) and module attributes.
                      </p>

                      <p>
                        Let’s go back to our calculator example and see how we can use them.
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre>defmodule Project.Calculator.Adder do

@moduledoc """ Provides adding functions for a calculator """

let’s have a version constant for this module to define its version

@version “1.0” @doc """ Calculate the sum of 2 numbers """ def add(a,b), do: a + b @doc """ Calculate the sum of 3 numbers """ def add(a, b, c), do: a + b + c @doc """ Return the version constant """ def version, do: @version end

                      <p>
                        There’s a bit to unpack from the above sample code (which you can paste into your iex shell and try out).
                      </p>

                      <p>
                        <code>@moduledoc</code> and <code>@doc</code> are called reserved attributes in Elixir and provide module documentation and function or macro documentation, respectively.<span class="intersentencespace"></span> We haven’t talked about macros yet, but we will in an upcoming chapter.<span class="intersentencespace"></span> For now, you can think of macros as a part of Elixir’s metaprogramming facilities.
                      </p>

                      <p>
                        <code>@version</code> is a custom module attribute that we defined to hold the “version” information for a module.<span class="intersentencespace"></span> We could have defined it to be a list or even a tuple.
                      </p>

                      <p>
                        Typically, Elixir developers use it as a temporary storage facility in a module (e.g., like a constant).
                      </p>
                    </div>

                    <div id="sec-anonymous_functions" data-tralics-id="cid33" class="section" data-number="8.4">
                      <h2>
                        <a href="#sec-anonymous_functions" class="heading hyperref"><span class="number">8.4 </span>Anonymous Functions</a>
                      </h2>

                      <p class="noindent">
                        One cool feature I like about Elixir is its ability to handle anonymous functions as first class citizens.
                      </p>

                      <p>
                        An anonymous function can be defined as follows.
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre># Let's define an anonymous function to compute the area of a triangle and bind it to area_triangle

area_triangle = fn(base, height) -> 0.5 _ base _ height end

Let’s define an anonymous function and adds the value of x to the value of whatever is computed by the anonymous function passed in via the areafunc parameter in addto_func

addtofunc = fn(x, areafunc) -> x + areafunc.(2, 1) end addtofunc.(2, area_triangle)

=> 3.0

It’s 3.0 because area_triangle computes a value of 1.0

                    <div id="cid34" data-tralics-id="cid34" class="section" data-number="8.5">
                      <h2>
                        <a href="#cid34" class="heading hyperref"><span class="number">8.5 </span>Summary</a>
                      </h2>

                      <p class="noindent">
                        Naming things is still a hard problem whether you’re doing functional programming or object-oriented programming.<span class="intersentencespace"></span> Fortunately, Elixir does give you tools to at least save you some typing when you are constructing module namespaces and re-using module functionality.
                      </p>

                      <div id="uid72" data-tralics-id="uid72" class="subsubsection" data-number="8.5.2.1">
                        <h4>
                          <a href="#uid72" class="heading">Footnotes</a>
                        </h4>
                      </div>
                    </div>

                    <div id="cha-8_footnotes">
                      <ol class="footnotes">
                        <li id="cha-8_footnote-1">
                          <a href="https://martinfowler.com/bliki/TwoHardThings.html" target="_blank" rel="noopener">Source: https://martinfowler.com/bliki/TwoHardThings.html</a> <a class="arrow" href="#cha-8_footnote-ref-1">↑</a>
                        </li>
                      </ol>
                    </div>

                    <div id="cha-chapter9" data-tralics-id="cid35" class="chapter" data-number="9">
                      <h1>
                        <a href="#cha-chapter9" class="heading hyperref"><span class="number">Chapter 9 </span>A Word On Types</a>
                      </h1>
                    </div>

                    <div id="cid36" data-tralics-id="cid36" class="section" data-number="9.1">
                      <h2>
                        <a href="#cid36" class="heading hyperref"><span class="number">9.1 </span>The First Thing I Do When Getting Started With a Programming Language</a>
                      </h2>

                      <p class="noindent">
                        Every program I’ve ever written comes down to dealing with data in some way.<span class="intersentencespace"></span> One of the first things I do when learning a new programming language is to get a sense of the data types available to me.<span class="intersentencespace"></span> For example, when I was doing Ruby on Rails work, and wanted to create database columns with numbers, I wanted to know how the Rails commands that auto-generated database table creation commands mapped to a database’s data types.
                      </p>

                      <p>
                        It’s also important to understand whether you’re dealing with a statically-typed language like Java, which means you have to declare upfront what type of variable it is (e.g., <em>int a = 2;</em>, which means a holds an integer), or a dynamically typed language like Ruby where variables can hold any kind of data.
                      </p>

                      <p>
                        Like Ruby, Elixir is a dynamically typed language.<span class="intersentencespace"></span> Unlike Erlang, Elixir will allow you to rebind a value to a variable.<span class="intersentencespace"></span> That’s why you can do:
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre>a = [1, 2, 3]

a = 2

                      <p>
                        So now it’s time to take a look at the data types available to you in Elixir.
                      </p>
                    </div>

                    <div id="sec-integer_float" data-tralics-id="cid37" class="section" data-number="9.2">
                      <h2>
                        <a href="#sec-integer_float" class="heading hyperref"><span class="number">9.2 </span>Integers and Floats</a>
                      </h2>

                      <p class="noindent">
                        Elixir has integers and floats as its primary way of representing numbers.<span class="intersentencespace"></span> And it has the Integer and Float modules with functions to allow you to work with those types.
                      </p>

                      <div id="uid73" data-tralics-id="uid73" class="subsection" data-number="9.2.1">
                        <h3>
                          <a href="#uid73" class="heading hyperref"><span class="number">9.2.1 </span>Arithmetic</a>
                        </h3>

                        <p class="noindent">
                          One nice feature Ruby gives you is the “%” or modulus operator for finding the remainder of a division operation.
                        </p>

                        <p>
                          Elixir gives you this through the “rem” function.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>rem(9, 3)

=> 0

rem(6, 4)

=> 2

                    <div id="sec-boolean" data-tralics-id="cid38" class="section" data-number="9.3">
                      <h2>
                        <a href="#sec-boolean" class="heading hyperref"><span class="number">9.3 </span>Boolean</a>
                      </h2>

                      <p class="noindent">
                        Elixir gives you <code>true</code> and <code>false</code> as boolean values.<span class="intersentencespace"></span> Interesting enough, they are equivalent to their respective atoms.
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre>true == :true

=> true

is_atom(true)

=> true

false == :false

=> false

                    <div id="cid39" data-tralics-id="cid39" class="section" data-number="9.4">
                      <h2>
                        <a href="#cid39" class="heading hyperref"><span class="number">9.4 </span>Atoms</a>
                      </h2>

                      <p class="noindent">
                        You’ve seen atom keys throughout this lesson in the various example map structures we’ve shown.
                      </p>

                      <p>
                        Elixir has a concept called atoms.<span class="intersentencespace"></span> An atom’s name is its value.<span class="intersentencespace"></span> If you’ve worked with the Ruby programming language, you’ll find they are analagous to Ruby symbols.<span class="intersentencespace"></span> If you’re coming from a language like Java or C++, I’m not sure there’s an equivalent analogy, so for clarity’s sake I’ll show a code example.
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre>m = %{:a => 1, :b => 2}
                      <p>
                        You can see in the above code example that :a and :b are both atom keys in a map.
                      </p>
                    </div>

                    <div id="cid40" data-tralics-id="cid40" class="section" data-number="9.5">
                      <h2>
                        <a href="#cid40" class="heading hyperref"><span class="number">9.5 </span>Strings</a>
                      </h2>

                      <p class="noindent">
                        Strings in Elixir are UTF-8 encoded and you use double quotes to represent them.
                      </p>

                      <p>
                        Note: single quotes denote character lists and mean something else entirely.
                      </p>
                    </div>

                    <div id="cid41" data-tralics-id="cid41" class="section" data-number="9.6">
                      <h2>
                        <a href="#cid41" class="heading hyperref"><span class="number">9.6 </span>Lists</a>
                      </h2>

                      <p class="noindent">
                        Lists are analogous to arrays in Ruby or other object-oriented languages like Java.<span class="intersentencespace"></span> We’ve seen them throughout the course in various examples.
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre># an example list

a = [1, 2, 3]

                    <div id="cid42" data-tralics-id="cid42" class="section" data-number="9.7">
                      <h2>
                        <a href="#cid42" class="heading hyperref"><span class="number">9.7 </span>Tuples</a>
                      </h2>

                      <p class="noindent">
                        One interesting type that you don’t have an analogy for as a Ruby programmer is the tuple.<span class="intersentencespace"></span> You define a tuple with curly braces.<span class="intersentencespace"></span> Tuples can hold any kind of value and store data contiguously in memory.
                      </p>

                      <p>
                        What does this mean practically?<span class="intersentencespace"></span> It means you can use the Kernel#elem method to get a tuple element by its index is a fairly fast operation.
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre>tuple = {:ok, 1, :msg, "abc"}

elem(tuple, 2)

=> :msg

                    <div id="cid43" data-tralics-id="cid43" class="section" data-number="9.8">
                      <h2>
                        <a href="#cid43" class="heading hyperref"><span class="number">9.8 </span>Summary</a>
                      </h2>

                      <p class="noindent">
                        Ok, so now you’ve been given a crash course on the types available to you in Elixir.<span class="intersentencespace"></span> Coming up, we’ll be looking at comprehensions and some other concepts before we head into your first project.
                      </p>
                    </div>

                    <div id="cha-chapter10" data-tralics-id="cid44" class="chapter" data-number="10">
                      <h1>
                        <a href="#cha-chapter10" class="heading hyperref"><span class="number">Chapter 10 </span>Elixir’s Comprehensions (Not Loops)</a>
                      </h1>
                    </div>

                    <div id="cid45" data-tralics-id="cid45" class="section" data-number="10.1">
                      <h2>
                        <a href="#cid45" class="heading hyperref"><span class="number">10.1 </span>The Misuse of Elixir’s Comprehensions</a>
                      </h2>

                      <p class="noindent">
                        So having some minor experience with Java and other object-oriented languages, I was curious if Elixir had a “for loop”, “while loop” or some other kind of looping construct.
                      </p>

                      <p>
                        And when I found the “for” keyword in Elixir, I thought “finally”.<span class="intersentencespace"></span> And of course I tried to use it like a “for loop” in an object-oriented language where I stored a piece of stateful information in a variable and expected it to be available later….Oops.<span class="intersentencespace"></span> I think I was trying to implement a version of the Traveling Salesman Algorithm.
                      </p>

                      <div id="uid74" data-tralics-id="uid74" class="subsection" data-number="10.1.1">
                        <h3>
                          <a href="#uid74" class="heading hyperref"><span class="number">10.1.1 </span>The Purpose of Comprehensions</a>
                        </h3>

                        <p class="noindent">
                          If you recall the Enum module in Elixir, there were sets of operations that allowed you to loop over a list/collection, and transform the list into another one.
                        </p>

                        <p>
                          Comprehensions are simply another way of doing this.<span class="intersentencespace"></span> The Elixir documentation refers to comprehensions as “syntactic sugar” for such operations.
                        </p>
                      </div>

                      <div id="uid75" data-tralics-id="uid75" class="subsection" data-number="10.1.2">
                        <h3>
                          <a href="#uid75" class="heading hyperref"><span class="number">10.1.2 </span>A Simple Example of a Comprehension</a>
                        </h3>

                        <p class="noindent">
                          To get an idea of what comprehensions can do, let’s look at a simple example.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>for x &lt;- [3, 4, 5], do: 2*x

=> [6, 8, 10]

                        <p>
                          As a comparison, you could have done the above example with a map such as in the below example.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>Enum.map([3, 4, 5], fn(x) -> 2*x end)

=> [6, 8, 10]

                      <div id="uid76" data-tralics-id="uid76" class="subsection" data-number="10.1.3">
                        <h3>
                          <a href="#uid76" class="heading hyperref"><span class="number">10.1.3 </span>Multiple Generators</a>
                        </h3>

                        <p class="noindent">
                          In the above example comprehension <em>x <- [3, 4, 5]</em> is referred to as a generator.<span class="intersentencespace"></span> You can have multiple generators in a comprehension.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>for x &lt;- [3, 4, 5], y &lt;- [1, 2], do: x + y

=> [4, 5, 5, 6, 6, 7]

                        <p>
                          You can see what happened.<span class="intersentencespace"></span> First, 3+1 and 3+2 were computed.<span class="intersentencespace"></span> Then 4+1 and 4+2 were computed.<span class="intersentencespace"></span> Finally, 5+1 and 5+2 were computed.
                        </p>
                      </div>

                      <div id="uid77" data-tralics-id="uid77" class="subsection" data-number="10.1.4">
                        <h3>
                          <a href="#uid77" class="heading hyperref"><span class="number">10.1.4 </span>Extracting Data Using Pattern Matching</a>
                        </h3>

                        <p class="noindent">
                          You can also use comprehensions in to transform a keyword list (list of tuples) into a different data structure, such as a list.<span class="intersentencespace"></span> If you look closely at the code below, you’ll notice you’re pattern matching.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>for {key, val} &lt;- [{:a, 1}, {:b, 4}, {:d, 6}], do: key

=> [:a, :b, :d]

                      <div id="uid78" data-tralics-id="uid78" class="subsection" data-number="10.1.5">
                        <h3>
                          <a href="#uid78" class="heading hyperref"><span class="number">10.1.5 </span>Filtering in Comprehensions</a>
                        </h3>

                        <p class="noindent">
                          If you recall from the article/video on Enum, there was a filter function that allowed you to select elements that met a certain condition.<span class="intersentencespace"></span> Comprehensions allow you to do this too.<span class="intersentencespace"></span> Look at the example below.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>import Integer

for {key, val} <- [{:a, 1}, {:b, 4}, {:d, 5}], is_odd(val), do: key

=> [:a, :d]

                        <p>
                          And with the above pattern matching and filtering mechanism provided to us by comprehensions, we select only the keys associated with odd values.
                        </p>
                      </div>

                      <div id="uid79" data-tralics-id="uid79" class="subsection" data-number="10.1.6">
                        <h3>
                          <a href="#uid79" class="heading hyperref"><span class="number">10.1.6 </span>Into a Map</a>
                        </h3>

                        <p class="noindent">
                          Let’s be honest.<span class="intersentencespace"></span> Sometimes you don’t want lists, you want a map.<span class="intersentencespace"></span> And you can have that with the handy <em>:into</em> option.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>for {key, val} &lt;- [{:a, 1}, {:b, 4}, {:d, 5}], into: %{}, do: {key, val}

=> %{a: 1, b: 4, d: 5}

                        <p>
                          In actuality, you can apply <em>:into</em> to any structure in Elixir that implements what’s known as the <em>Collectable</em> protocol.<span class="intersentencespace"></span> We are going to touch on protocols in an upcoming section, so I will hold off on defining them for now.<span class="intersentencespace"></span> Suffice it to say, you can pass in a list, map, or string into the <em>:into</em> option.
                        </p>
                      </div>
                    </div>

                    <div id="cid46" data-tralics-id="cid46" class="section" data-number="10.2">
                      <h2>
                        <a href="#cid46" class="heading hyperref"><span class="number">10.2 </span>Summary</a>
                      </h2>

                      <p class="noindent">
                        So hopefully you’ve gotten a good overview of what you can do with comprehensions.<span class="intersentencespace"></span> And the next time you see the <em>for</em> keyword in an Elixir program, think “comprehension” not “for loop”.
                      </p>
                    </div>

                    <div id="cha-chapter11" data-tralics-id="cid47" class="chapter" data-number="11">
                      <h1>
                        <a href="#cha-chapter11" class="heading hyperref"><span class="number">Chapter 11 </span>Strings in Elixir</a>
                      </h1>
                    </div>

                    <div id="cid48" data-tralics-id="cid48" class="section" data-number="11.1">
                      <h2>
                        <a href="#cid48" class="heading hyperref"><span class="number">11.1 </span>When IO.inspect Let Me Down With a Character List</a>
                      </h2>

                      <p class="noindent">
                        So in other languages, sometimes you want to output the contents of an array to see what it contains.<span class="intersentencespace"></span> For example, in the Ruby programming language, if I have an array <em>a = [8, 9, 10, 11]</em>, I can do the following.
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre>a = [8, 9, 10, 11]

a.inspect

=> [8, 9, 10, 11]

                      <p>
                        Notice how I can see the array contains 8, 9, 10, and 11.
                      </p>

                      <p>
                        When I started with Elixir, I found I could more or less do the same thing with <em>IO.inspect</em>.<span class="intersentencespace"></span> But one day, I was let down with a surprise.<span class="intersentencespace"></span> I did the following.
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre>a = [8, 9, 10, 11]

IO.inspect a

=> ‘\b\t\n\v’

                      <p>
                        WTF is going on?
                      </p>

                      <div id="uid80" data-tralics-id="uid80" class="subsection" data-number="11.1.1">
                        <h3>
                          <a href="#uid80" class="heading hyperref"><span class="number">11.1.1 </span>But first, we need to talk about binaries</a>
                        </h3>

                        <p class="noindent">
                          To answer that, we have to learn about binaries.<span class="intersentencespace"></span> A binary is simply a sequence of bytes in Elixir.<span class="intersentencespace"></span> And a byte is simply 8 bits.<span class="intersentencespace"></span> And in computer-ese, a bit is simply a 0 or 1.
                        </p>
                      </div>

                      <div id="uid81" data-tralics-id="uid81" class="subsection" data-number="11.1.2">
                        <h3>
                          <a href="#uid81" class="heading hyperref"><span class="number">11.1.2 </span>Let’s see how to represent a binary with actual code</a>
                        </h3>

                        <p class="noindent">
                          Below is a code block that shows you how to represent a binary.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>binary_example = &lt;&lt;65, 66, 68>>
                        <p>
                          Now, the double angled brackets (<em>« »</em>) defines a new bitstring.<span class="intersentencespace"></span> Each bitstring is composed of many segments, each of which has a type.<span class="intersentencespace"></span> There are 9 types of segments that can be used in bitstrings including integer, float, utf8, utf16, and utf32.
                        </p>
                      </div>

                      <div id="uid82" data-tralics-id="uid82" class="subsection" data-number="11.1.3">
                        <h3>
                          <a href="#uid82" class="heading hyperref"><span class="number">11.1.3 </span>What does this have to do with strings again?</a>
                        </h3>

                        <p class="noindent">
                          Strings are a subset of binaries.<span class="intersentencespace"></span> Specifically, strings are a valid UTF-8 sequence of bytes.<span class="intersentencespace"></span> How do you know if you have a valid string on your hands?<span class="intersentencespace"></span> Fortunately, Elixir’s String module gives you a way with the <em>valid?</em><span class="intersentencespace"></span> method.
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>binary_example = &lt;&lt;65, 66, 68>>

String.valid? binary_example

=> true

                      <div id="uid83" data-tralics-id="uid83" class="subsection" data-number="11.1.4">
                        <h3>
                          <a href="#uid83" class="heading hyperref"><span class="number">11.1.4 </span>Single versus double quotes</a>
                        </h3>

                        <p class="noindent">
                          The other thing you’ll notice when dealing with strings in Elixir is the double-quoted and single-quoted strings.
                        </p>
                      </div>

                      <div id="uid84" data-tralics-id="uid84" class="subsection" data-number="11.1.5">
                        <h3>
                          <a href="#uid84" class="heading hyperref"><span class="number">11.1.5 </span>Properties of double-quoted strings.</a>
                        </h3>

                        <p class="noindent">
                          Before we dive into what single-quoted strings are, let’s talk about what you can do with double-quoted strings in Elixir.<span class="intersentencespace"></span> Here are the two most common use cases.
                        </p>

                        <div id="uid85" data-tralics-id="uid85" class="subsubsection" data-number="11.1.5.1">
                          <h4>
                            <a href="#uid85" class="heading">Common Use Case 1: Variable Interpolation</a>
                          </h4>

                          <p class="noindent">
                            In some of the production-grade Phoenix web applications I’ve been writing, I’ve found variable interpolations in strings quite handy.<span class="intersentencespace"></span> For example, if I want to embed a dynamic link URL that changes depending on what “category” it is, I might do something as shown in the below code block.
                          </p>

                          <div class="code">
                            <div class="highlight">
                              <pre>category = "food"

url = ”http://www.foodie.com/#{category}

                          <p>
                            If you’re familiar with a dynamic object-oriented language like Ruby, then this style of interpolation might look quite familiar to you.
                          </p>

                          <p>
                            You can also think of variable interpolation as an alternative way to concatenate strings.
                          </p>

                          <p>
                            For example, this is the “regular” way to concatenate strings:
                          </p>

                          <div class="code">
                            <div class="highlight">
                              <pre>b = "world"

“hello ” <> b

                          <p>
                            But you could also do it this way:
                          </p>

                          <div class="code">
                            <div class="highlight">
                              <pre>b = "world"

“hello #{b}”

                        <div id="uid86" data-tralics-id="uid86" class="subsubsection" data-number="11.1.5.2">
                          <h4>
                            <a href="#uid86" class="heading">Common Use Case 2: Documentation</a>
                          </h4>

                          <p class="noindent">
                            In Elixir modules, you’ll often see strings used to document modules.<span class="intersentencespace"></span> Below is an example from a hex package I wrote called <a href="https://github.com/treble37/nested_filter" target="_blank" rel="noopener">nested_filter</a>.
                          </p>

                          <div class="code">
                            <div class="highlight">
                              <pre>@doc """

Take a (nested) map and filter out any keys with specified values in the valuestoreject list. """ @spec dropbyvalue(%{any => any}, [any]) :: %{any => any} def dropbyvalue(map, valuestoreject) when ismap(map) do drop_by(map, fn (, val) -> val in valuestoreject end) end

                      <div id="uid87" data-tralics-id="uid87" class="subsection" data-number="11.1.6">
                        <h3>
                          <a href="#uid87" class="heading hyperref"><span class="number">11.1.6 </span>Single-quoted strings are character lists</a>
                        </h3>

                        <p class="noindent">
                          Remember from the paragraphs above how inspecting a list of integers produced the following?
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>a = [8, 9, 10, 11]

IO.inspect a

=> ‘\b\t\n\v’

                        <p>
                          Each of those characters is a codepoint, or a character.<span class="intersentencespace"></span> Each codepoint is represented by what’s known as a code unit, which refers to the number of bits an encoding uses.<span class="intersentencespace"></span> Examples of encodings include UTF-8 (8 bit encoding) and UTF-16 (16 bit encoding).
                        </p>

                        <p>
                          So when Elixir prints out a character list like the above example, it really prints out the UTF-8 codepoints that the character list of integers represents.
                        </p>

                        <div id="uid88" data-tralics-id="uid88" class="subsubsection" data-number="11.1.6.1">
                          <h4>
                            <a href="#uid88" class="heading">How do you avoid printing out the character representations?</a>
                          </h4>

                          <p class="noindent">
                            Before I tell you, let me show you a really cool trick.<span class="intersentencespace"></span> Boot up an “iex” prompt and type <em>h Inspect.Opts</em>.
                          </p>

                          <p>
                            You should see something like:
                          </p>

                          <div class="code">
                            <div class="highlight">
                              <pre>Inspect.Opts

Defines the Inspect.Opts used by the Inspect protocol.

The following fields are available:

• :structs - when false, structs are not formatted by the inspect protocol, they are instead printed as maps, defaults to true. • :binaries - when :asstrings all binaries will be printed as strings, non-printable bytes will be escaped. When :asbinaries all binaries will be printed in bit syntax.

When the default :infer, the binary will be printed as a string if it is
printable, otherwise in bit syntax.

• :charlists - when :ascharlists all lists will be printed as char lists, non-printable elements will be escaped. When :aslists all lists will be printed as lists.

When the default :infer, the list will be printed as a charlist if it is
printable, otherwise as list.

• :limit - limits the number of items that are printed for tuples, bitstrings, maps, lists and any other collection of items. It does not apply to strings nor charlists and defaults to 50. • :printablelimit - limits the number of bytes that are printed for strings and char lists. Defaults to 4096. • :pretty - if set to true enables pretty printing, defaults to false. • :width - defaults to 80 characters, used when pretty is true or when printing to IO devices. Set to 0 to force each item to be printed on its own line. • :base - prints integers as :binary, :octal, :decimal, or :hex, defaults to :decimal. When inspecting binaries any :base other than :decimal implies binaries: :asbinaries. • :safe - when false, failures while inspecting structs will be raised as errors instead of being wrapped in the Inspect.Error exception. This is useful when debugging failures and crashes for custom inspect implementations • :syntax_colors - when set to a keyword list of colors the output will be colorized. The keys are types and the values are the colors to use for each type. e.g. [number: :red, atom: :blue]. Types can include :number, :atom, regex, :tuple, :map, :list, and :reset. Colors can be any t:IO.ANSI.ansidata/0 as accepted by IO.ANSI.format/1.

                          <p>
                            Notice the “:as_lists” argument you can pass to the “:charlists” option.<span class="intersentencespace"></span> The following code example illustrates this:
                          </p>

                          <div class="code">
                            <div class="highlight">
                              <pre>binary_example = [98, 101, 100]

IO.inspect binary_example

=> ‘bed’

IO.inspect binaryexample, charlists: :aslists

=> [98, 101, 100]

                          <p>
                            When you pass in the “:as_lists” argument, you get back a list of integers from calling IO.inspect.
                          </p>

                          <p>
                            Note: the :as_lists option is for Elixir >= 1.5.<span class="intersentencespace"></span> According to this stackoverflow post<sup id="cha-11_footnote-ref-1" class="footnote"><a href="#cha-11_footnote-1">1</a></sup>, with Elixir < 1.4, pass “false” as an argument to the “:char_lists” option.
                          </p>

                          <p>
                            You previously saw this before in the discussion of double-quoted strings, but I’ll include the example below again for convenience.
                          </p>

                          <div class="code">
                            <div class="highlight">
                              <pre>@doc """

Take a (nested) map and filter out any keys with specified values in the valuestoreject list. """ @spec dropbyvalue(%{any => any}, [any]) :: %{any => any} def dropbyvalue(map, valuestoreject) when ismap(map) do drop_by(map, fn (, val) -> val in valuestoreject end) end

                      <div id="sec-heredocs" data-tralics-id="uid90" class="subsection" data-number="11.1.7">
                        <h3>
                          <a href="#sec-heredocs" class="heading hyperref"><span class="number">11.1.7 </span>Heredocs</a>
                        </h3>

                        <p class="noindent">
                          Finally, no discussion of strings would be complete without at least mentioning Heredocs.<span class="intersentencespace"></span> Heredocs are multiline strings which are used to document code in Elixir (at least, that’s the way I’ve mostly seen them).
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre>@doc """

Output hello world message """ def hello_world, do: “hello world”

                      <div id="uid91" data-tralics-id="uid91" class="subsection" data-number="11.1.8">
                        <h3>
                          <a href="#uid91" class="heading hyperref"><span class="number">11.1.8 </span>Some Interesting Reference Links</a>
                        </h3>

                        <p class="noindent">
                          These are some of the references I used when making this post.
                        </p>

                        <p>
                          <a href="http://culttt.com/2016/03/21/working-strings-elixir/" target="_blank" rel="noopener">http://culttt.com/2016/03/21/working-strings-elixir/</a><br /> <a href="https://medium.com/@harry_dev/elixir-for-rubyists-charlists-binarys-strings-iolists-eeacf38db999" target="_blank" rel="noopener">https://medium.com/@harry_dev/elixir-for-rubyists-charlists-binarys-strings-iolists-eeacf38db999</a><br /> <a href="https://www.bignerdranch.com/blog/elixir-and-io-lists-part-1-building-output-efficiently/" target="_blank" rel="noopener">https://www.bignerdranch.com/blog/elixir-and-io-lists-part-1-building-output-efficiently/</a><br /> <a href="https://www.bignerdranch.com/blog/elixir-and-io-lists-part-2-io-lists-in-phoenix/" target="_blank" rel="noopener">https://www.bignerdranch.com/blog/elixir-and-io-lists-part-2-io-lists-in-phoenix/</a>
                        </p>
                      </div>
                    </div>

                    <div id="cha-11_footnotes">
                      <ol class="footnotes">
                        <li id="cha-11_footnote-1">
                          <a href="https://stackoverflow.com/questions/30037914/elixir-lists-interpreted-as-char-lists" target="_blank" rel="noopener">Source: Stackoverflow post on char lists</a> <a class="arrow" href="#cha-11_footnote-ref-1">↑</a>
                        </li>
                      </ol>

                      <p>
                        <a href='https://binarywebpark.clickfunnels.com/optinsurvey8kfrv6j4' target='_blank'><img src="http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px.png" alt="" width="800" height="800" class="alignnone size-full wp-image-1723" srcset="http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px.png 800w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-150x150.png 150w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-300x300.png 300w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-768x768.png 768w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-550x550.png 550w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-500x500.png 500w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-225x225.png 225w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-200x200.png 200w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-400x400.png 400w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-260x260.png 260w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-600x600.png 600w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_drink_cta_blog800px-414x414.png 414w" sizes="(max-width: 800px) 100vw, 800px" /></a>
                      </p>
                    </div>

                    <div id="cha-chapter11" data-tralics-id="cid49" class="chapter" data-number="12">
                      <h1>
                        <a href="#cha-chapter11" class="heading hyperref"><span class="number">Chapter 12 </span>What Open Source Taught Me About the Basics of Documentation In Elixir</a>
                      </h1>
                    </div>

                    <div id="sec-timex" data-tralics-id="cid50" class="section" data-number="12.1">
                      <h2>
                        <a href="#sec-timex" class="heading hyperref"><span class="number">12.1 </span>Looking at Timex</a>
                      </h2>

                      <p class="noindent">
                        When I first started learning about Elixir, one of the first open source libraries I came across was <a href="https://github.com/bitwalker/timex" target="_blank" rel="noopener">Timex</a>.<span class="intersentencespace"></span> Within that library, I came across the [Types module[(https://github.com/bitwalker/timex/blob/master/lib/timex/types.ex){:target=”_blank”}.
                      </p>

                      <p>
                        Within that library, I saw the following code…
                      </p>

                      <div class="code">
                        <div class="highlight">
                          <pre>defmodule Timex.Types do

Date types

@type year :: Calendar.year @type month :: Calendar.month @type day :: Calendar.day @type numofdays :: 28..31 @type daynum :: 1..366 @type weekofmonth :: 1..5 @type weekday :: 1..7 @type weeknum :: 1..53

Time types

@type hour :: Calendar.hour @type minute :: Calendar.minute @type second :: Calendar.second @type microsecond :: Calendar.microsecond @type timestamp :: {megaseconds, seconds, microseconds } @type megaseconds :: nonneginteger @type seconds :: nonneginteger @type microseconds :: nonneginteger

some code was left out for brevity…

end

                      <p>
                        And I wondered what is this “@type” syntax?
                      </p>
                    </div>

                    <div id="sec-documentation_first_class" data-tralics-id="cid51" class="section" data-number="12.2">
                      <h2>
                        <a href="#sec-documentation_first_class" class="heading hyperref"><span class="number">12.2 </span>The Philosophy of Documentation as a First Class Citizen</a>
                      </h2>

                      <p class="noindent">
                        Before we get to the actual way to write documentation in Elixir, let’s briefly dive into a phrase you’ll often hear – “documentation as a first class citizen.”<span class="intersentencespace"></span> What does this mean?<span class="intersentencespace"></span> From Elixir’s <a href="https://hexdocs.pm/elixir/writing-documentation.html" target="_blank" rel="noopener">documentation itself</a>, it means “documentation should be easy to write and easy to read.”
                      </p>
                    </div>

                    <div id="sec-markdown" data-tralics-id="cid52" class="section" data-number="12.3">
                      <h2>
                        <a href="#sec-markdown" class="heading hyperref"><span class="number">12.3 </span>The Syntax for Writing Documentation - Markdown</a>
                      </h2>

                      <p class="noindent">
                        The way to write documentation in Elixir is by using markdown syntax.<span class="intersentencespace"></span> There are plenty of tutorials <a href="https://help.github.com/articles/basic-writing-and-formatting-syntax/" target="_blank" rel="noopener">such as this one by GitHub that cover this syntax</a>, but I’ll give you a quick overview to get started.
                      </p>

                      <p>
                        Markdown is simply a shorthand syntax that eventually gets parsed into HTML.
                      </p>

                      <div id="uid92" data-tralics-id="uid92" class="subsection" data-number="12.3.1">
                        <h3>
                          <a href="#uid92" class="heading hyperref"><span class="number">12.3.1 </span>Headings</a>
                        </h3>

                        <p class="noindent">
                          The pound sign (#) is used to create HTML heading tags.<span class="intersentencespace"></span> One pound sign is equivalent to an “h1” tag and six pounds signs is a “h6” tag.
                        </p>
                      </div>

                      <div id="uid93" data-tralics-id="uid93" class="subsection" data-number="12.3.2">
                        <h3>
                          <a href="#uid93" class="heading hyperref"><span class="number">12.3.2 </span>Code blocks</a>
                        </h3>

                        <p class="noindent">
                          You can use backticks (‘) to specify blocks of code that will be prefaced with “pre” or “code” tags when converted to HTML.
                        </p>

                        <blockquote class="quotation">
                          <p class="quote">
                            <code>&lt;br />

defmodule DemoCode do<br /> def hello, do: “hello”<br /> end<br />

                      <div id="uid94" data-tralics-id="uid94" class="subsection" data-number="12.3.3">
                        <h3>
                          <a href="#uid94" class="heading hyperref"><span class="number">12.3.3 </span>Lists</a>
                        </h3>

                        <p class="noindent">
                          Since markdown gets converted to HTML, you can have ordered and unordered lists.
                        </p>

                        <div id="uid95" data-tralics-id="uid95" class="subsubsection" data-number="12.3.3.1">
                          <h4>
                            <a href="#uid95" class="heading">Ordered Lists</a>
                          </h4>

                          <p class="noindent">
                            For ordered lists, you use numbers followed by periods.<span class="intersentencespace"></span> For example:
                          </p>

                          <blockquote class="quotation">
                            <ol>
                              <li>
                                item 1
                              </li>
                              <li>
                                item 2
                              </li>
                              <li>
                                item 3
                              </li>
                            </ol>
                          </blockquote>
                        </div>

                        <div id="uid99" data-tralics-id="uid99" class="subsubsection" data-number="12.3.3.2">
                          <h4>
                            <a href="#uid99" class="heading">Unordered Lists</a>
                          </h4>

                          <p class="noindent">
                            For unordered lists, you use pluses, asterisks, or hypens.<span class="intersentencespace"></span> For example:
                          </p>

                          <blockquote class="quotation">
                            <ul>
                              <li>
                                item 1
                              </li>
                              <li>
                                item 2
                              </li>
                              <li>
                                item 3
                              </li>
                            </ul>
                          </blockquote>
                        </div>
                      </div>

                      <div id="uid103" data-tralics-id="uid103" class="subsection" data-number="12.3.4">
                        <h3>
                          <a href="#uid103" class="heading hyperref"><span class="number">12.3.4 </span>Basic Styling of Text</a>
                        </h3>

                        <p class="noindent">
                          If you need to italicize text, use asterisks or single underscores.<span class="intersentencespace"></span> For example:
                        </p>

                        <blockquote class="quotation">
                          <p class="quote">
                            *This text will be put into an <em> tag*.</em>
                          </p>
                        </blockquote>

                        <p>
                          You’ll end up with html that looks like:
                        </p>

                        <div class="code">
                          <div class="highlight">
                            <pre><em>This text will be put into an <em> tag

12.3.5 External Hyperlinks

If you need to annotate a hyperlink in markdown, you use square brackets that enclose descriptive text surrounded by parentheses that contain the hyperlink.

It looks like the following:

This link goes to my blog post on nested filter.

Ok, so now you have a brief overview of markdown. It’s time to start documenting!

12.4 Documenting Your Elixir Code

Erlang has the notion of something called module attributes that applies in Elixir. In Elixir code, module attributes are often used to define constants or as a temporary storage holder for values to be used during code compilation.

When documenting Elixir code, you’ll rely a lot on the reserved attributes “@moduledoc” and “@doc”.

12.4.1 Documenting Modules

<p class="noindent">
  When documenting modules, you’ll use the @moduledoc attribute.<span class="intersentencespace"></span> The following is an example.
</p>


<div class="code">
  <div class="highlight">
    <pre>defmodule HelloWorld do

@moduledoc """ This is the HelloWorld module """

def helloworld, do: “helloworld” end

  </div>

</div>


<p>
  What if you didn’t wish to document this module?
</p>


<p>
  Then you could set @moduledoc to false.<span class="intersentencespace"></span> So it would look like this:
</p>


<div class="code">
  <div class="highlight">
    <pre>defmodule HelloWorld do

@moduledoc false

def helloworld, do: “helloworld” end

  </div>

</div>


<div id="uid106" data-tralics-id="uid106" class="subsubsection" data-number="12.4.1.1">
  <h4>
    <a href="#uid106" class="heading">Documenting Modules With Style</a>
  </h4>


  <p class="noindent">
    Believe it or not, there is a proper style to document modules via this <a href="https://github.com/christopheradams/elixir_style_guide#documentation" target="_blank" rel="noopener">community style guide</a>.<span class="intersentencespace"></span> Right now Elixir is pretty new, so this could change, but I think it serves as good guidance for now.
  </p>


  <p>
    The basic tenets are:
  </p>


  <ul>
    <li>
      The @moduledoc attribute should be included right after the “defmodule” line.<span class="intersentencespace"></span>

    </li>


    <li>
      Separate the @moduledoc documentation with a blank line between the end of the documentation and new code.<span class="intersentencespace"></span>

    </li>


    <li>
      Be sure to use heredocs for the description text for @moduledoc.<span class="intersentencespace"></span>

    </li>

  </ul>

</div>

12.4.2 Documenting Functions

<p class="noindent">
  When documenting functions, you’ll use the @doc attribute.<span class="intersentencespace"></span> We now document the function in the HelloWorld module in the following example.
</p>


<div class="code">
  <div class="highlight">
    <pre>defmodule HelloWorld do

@moduledoc """ This is the HelloWorld module """

@doc """ Says hello_world

Returns “hello_world”

Examples

iex> HelloWorld.hello_world
hello_world

"""

def helloworld, do: “helloworld” end

  </div>

</div>


<p>
  What if you didn’t want to document this function?<span class="intersentencespace"></span> Similar to module documentation, you can set @doc to false.
</p>

12.4.3 A Word on Documenting Private Functions

<p class="noindent">
  So the big deal here is that you can’t.<span class="intersentencespace"></span> You’ll get a stern warning from Elixir and your documentation description will be ignored.
</p>

12.4.4 Typespecs

<p class="noindent">
  Remember how I mentioned the Timex library?
</p>


<p>
  Even though Elixir is a dynamically typed language, it still gives you functionality for documenting typed function signatures and declaring custom types.
</p>


<p>
  Declaring custom types is what the Types module in the Timex library did.
</p>


<div id="uid113" data-tralics-id="uid113" class="subsubsection" data-number="12.4.4.1">
  <h4>
    <a href="#uid113" class="heading">@type attribute</a>
  </h4>


  <p class="noindent">
    To understand the @type attribute for declaring custom data types, let’s look at a portion of the Timex.Types module again.
  </p>


  <div class="code">
    <div class="highlight">
      <pre>defmodule Timex.Types do

Time types

@type timestamp :: {megaseconds, seconds, microseconds } @type megaseconds :: nonneginteger @type seconds :: nonneginteger @type microseconds :: nonneginteger

some code was left out for brevity…

end

    </div>

  </div>


  <p>
    Notice the types megaseconds, seconds, and microseconds.<span class="intersentencespace"></span> They are defined as a “non_neg_integer”.<span class="intersentencespace"></span> Now a “non_neg_integer” is a built-in type specification.<span class="intersentencespace"></span> You’ll find that Elixir steals a lot of its built-in type specifications from Erlang and expresses it the same way.
  </p>


  <p>
    Now notice the timestamp type.<span class="intersentencespace"></span> This is the custom day type that is defined.<span class="intersentencespace"></span> It is a tuple composed of the built-in types.
  </p>

</div>


<div id="uid114" data-tralics-id="uid114" class="subsubsection" data-number="12.4.4.2">
  <h4>
    <a href="#uid114" class="heading">Basic Types in Elixir Documentation</a>
  </h4>


  <p class="noindent">
    I’m printing out the basic types in Elixir here as a convenience.<span class="intersentencespace"></span> I pulled it from the <a href="https://hexdocs.pm/elixir/typespecs.html#types-and-their-syntax" target="_blank" rel="noopener">Hex docs</a>.
  </p>


  <div class="code">
    <div class="highlight">
      <pre>type :: any()                   # the top type, the set of all terms
 :: none()                  # the bottom type, contains no terms
 :: atom()
 :: map()                   # any map
 :: pid()                   # process identifier
 :: port()
 :: reference()
 :: struct()                # any struct
 :: tuple()                 # tuple of any size

 ::                         ## Numbers
 :: float()
 :: integer()
 :: neg_integer()           # ..., -3, -2, -1
 :: non_neg_integer()       # 0, 1, 2, 3, ...
 :: pos_integer()           # 1, 2, 3, ...

 ::                                             ## Lists
 :: list(type)                                  # proper list ([]-terminated)
 :: nonempty_list(type)                         # non-empty proper list
 :: maybe_improper_list(type1, type2)           # proper or improper list
 :: nonempty_improper_list(type1, type2)        # improper list
 :: nonempty_maybe_improper_list(type1, type2)  # non-empty proper or improper list

 :: Literals                # Described in section "Literals"
 :: Builtin                 # Described in section "Built-in types"
 :: Remotes                 # Described in section "Remote types"
 :: UserDefined             # Described in section "User-defined types"
    </div>

  </div>

</div>


<div id="uid115" data-tralics-id="uid115" class="subsubsection" data-number="12.4.4.3">
  <h4>
    <a href="#uid115" class="heading">@spec and @typedoc attributes</a>
  </h4>


  <p class="noindent">
    Now let’s look at how to use @spec and @typedoc.
  </p>


  <div class="code">
    <div class="highlight">
      <pre>defmodule HelloWorld do

@moduledoc """ This is the HelloWorld module """

@doc """ Prints a hello message

Parameters

- number: integer that will be interpolated in the hello message

Examples

iex> HelloWorld.hello_number(2)
"hello 2"

"""

@typedoc “The number to be used with the hello message” @type num :: integer() | float()

@spec hellonumber(num) :: String.t def hellonumber(number), do: “hello #{number}” end

    </div>

  </div>


  <p>
    Note that @typedoc is used to describe the @type you’re defining.
  </p>


  <p>
    The @spec is being used to specify the function specification.
  </p>


  <p>
    From a proper coding convention perspective, note that we group @typedoc and @type together and separate it from additional code with a blank line and we keep @spec directly above the function definition with no blank line.
  </p>

</div>


<div id="uid116" data-tralics-id="uid116" class="subsubsection" data-number="12.4.4.4">
  <h4>
    <a href="#uid116" class="heading">@opaque and @typep</a>
  </h4>


  <p class="noindent">
    So two module attributes worth mentioning that I didn’t know about when I first started learning Elixir are @opaque and @typep.
  </p>


  <p>
    Now any type defined via @typep is considered private.
  </p>


  <p>
    @opaque is used to define a public facing type while keeping the structure of the type out of the public documentation.
  </p>

</div>

12.5 Writing Documentation Tests in Phoenix and Elixir

If you’re interested in understanding how to write documentation tests in Elixir, check out this blog post I wrote.

12.6 Documentation NestedFilter and Digger

In learning about Elixir I wrote two hex packages. One was nested_filter and the other was digger. They both contain examples on how to document your Elixir code. If you notice an issue, pull requests are welcome!

12.6.1 Summary

<p class="noindent">
  Hopefully you now have a feel for how to document your Elixir code.<span class="intersentencespace"></span> Even though Elixir is a dynamically typed language, it still gives you the ability to specify your data types via documentation.<span class="intersentencespace"></span> I really like this because I feel like it can help make the intent of your code more clear.
</p>

Chapter 13 Chapter 12 A Tour of The Kernel Module

13.1 Where does to_atom come from?

As I dove deeper into Elixir, I started using guard clauses. So I would end up writing functions with guard clauses that looked like the following:

defmodule Example do
  def hello(n) when is_atom(n), do: :hello
  def hello(n) when is_list(n), do: ["h", "e", "l", "l", "o"]
end
</div>

One day I started wondering where functions like is_atom were coming from and why I never had to call out a module name to have access to them, the way I would have to do with Enum.map/1 as an example.

For the next few sections, we’re going to talk about some interesting Kernel functions and cover guard clauses.

13.2 Diving Into Kernel’s Interesting Functions

The Kernel module has some useful functions that are handy to know as you’re going about your day to day Elixir programming.

13.2.1 The is_* functions

<p class="noindent">
  The first set of functions that are handy are what I affectionately term the “is_*” (pronounced “is star”) functions.
</p>


<p>
  Here’s a list and their description straight from the Elixir documentation:
</p>


<ol>
  <li>
    is_atom - Returns <code>true</code> if <code>term</code> is an atom; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_binary - Returns <code>true</code> if <code>term</code> is a binary; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_bitstring - Returns <code>true</code> if <code>term</code> is a bitstring (including a binary); otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_boolean - Returns <code>true</code> if <code>term</code> is a floating-point number; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_float - Returns <code>true</code> if <code>term</code> is a floating-point number; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_function - Returns <code>true</code> if <code>term</code> is a function; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_integer - Returns <code>true</code> if <code>term</code> is an integer; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_list - Returns <code>true</code> if <code>term</code> is a list with zero or more elements; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_number - Returns <code>true</code> if <code>term</code> is either an integer or a floating-point number; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_pid - Returns <code>true</code> if <code>term</code> is a PID (process identifier); otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_port - Returns <code>true</code> if <code>term</code> is a port identifier; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_tuple - Returns <code>true</code> if <code>term</code> is a tuple; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_map - Returns <code>true</code> if <code>term</code> is a map; otherwise returns <code>false</code>.<span class="intersentencespace"></span>

  </li>


  <li>
    is_nil - Returns <code>true</code> if <code>term</code> is <code>nil</code>, <code>false</code> otherwise.<span class="intersentencespace"></span>

  </li>

</ol>

13.2.2 Binaries and Bitstrings: A Simple Explanation

<p class="noindent">
  One point that deserves a bit of further elaboration is the difference between binaries and bitstrings.
</p>


<p>
  Let’s look at an example in code.
</p>


<div class="code">
  <div class="highlight">
    <pre>  iex> is_bitstring "hello"

=> true

iex> is_bitstring <<1::2>>

=> true

iex> is_bitstring <<1::8>>

=> true

iex> is_binary “hello”

=> true

iex> is_binary <<1::2>>

=> false

iex> is_binary <<1::8>>

=> true

iex> bit_size “hello”

=> 40

iex> bit_size <<1::2>>

=> 1

iex> bit_size <<1::8>>

=> 8

  </div>

</div>


<p>
  There’s a wonderful explanation from this <a href="https://elixirforum.com/t/bitstring-and-binary/2351/4" target="_blank" rel="noopener">forum post</a> that describes this perfectly that I will quote here:
</p>


<blockquote class="quotation">
  <p class="quote">
    In Elixir, a “bitstring” is anything between <> markers, and it contains a contiguous series of bits in memory.<span class="intersentencespace"></span> If there happen to be 8 of those bits, or 16, or any other number divisible by 8, we call that bitstring a “binary” - a series of bytes.<span class="intersentencespace"></span> And if those bytes are valid UTF-8, we call that binary a “string”.<span class="intersentencespace"></span>
  </p>

</blockquote>


<p>
  What does that mean for our example?
</p>


<p>
  Think of strings as a subset of all binaries, and binaries as a subset of all bitstrings.<span class="intersentencespace"></span> So from the example, you can see that “hello” is 40 bytes long which is divisible by 8.<span class="intersentencespace"></span> So it is a binary and since it is also valid UTF-8, it is also a string.
</p>

13.2.3 The data structure functions

<p class="noindent">
  There’s some other interesting functions that have to do with maps and lists, so I call them the “data structure functions”.<span class="intersentencespace"></span> Here they are with a description for your convenience.
</p>


<ol>
  <li>
    bit_size - Returns an integer which is the size in bits of bitstring.<span class="intersentencespace"></span>

  </li>


  <li>
    byte_size - Returns the number of bytes needed to contain bitstring.<span class="intersentencespace"></span>

  </li>


  <li>
    elem - Gets the element at the zero-based index in tuple.<span class="intersentencespace"></span>

  </li>


  <li>
    get_in/2 - Gets a value from a nested structure.<span class="intersentencespace"></span>

  </li>


  <li>
    hd - Returns the head of a list.<span class="intersentencespace"></span>

  </li>


  <li>
    length - Returns the length of list.<span class="intersentencespace"></span>

  </li>


  <li>
    pop_in - Pops a key from the given nested structure.<span class="intersentencespace"></span>

  </li>


  <li>
    put_elem/3 - Inserts value at the given zero-based index in tuple.<span class="intersentencespace"></span>

  </li>


  <li>
    put_in/3 - Puts a value in a nested structure.<span class="intersentencespace"></span>

  </li>


  <li>
    tuple_size/1 - Returns the size of a tuple.<span class="intersentencespace"></span>

  </li>


  <li>
    update_in/3 - Updates a key in a nested structure.<span class="intersentencespace"></span>

  </li>


  <li>
    map_size/1 - Returns the size of a map.<span class="intersentencespace"></span>

  </li>


  <li>
    tl - Returns the tail of a list.<span class="intersentencespace"></span>

  </li>

</ol>

13.2.4 The math functions

<p class="noindent">
  There’s some other interesting functions that have to do with arithmetic, so I call them the “math functions”.<span class="intersentencespace"></span> Here they are with a description for your convenience.
</p>


<ol>
  <li>
    div/2 - Performs an integer division.<span class="intersentencespace"></span>

  </li>


  <li>
    round/1 - Rounds a number to the nearest integer.<span class="intersentencespace"></span>

  </li>


  <li>
    max/2 - Returns the biggest of the two given terms according to Erlang’s term ordering.<span class="intersentencespace"></span>

  </li>


  <li>
    min/2 - Returns the smallest of the two given terms according to Erlang’s term ordering.<span class="intersentencespace"></span>

  </li>


  <li>
    +/2 - Arithmetic addition.<span class="intersentencespace"></span>

  </li>


  <li>
    */2 - Arithmetic multiplication.<span class="intersentencespace"></span>

  </li>


  <li>
    //2 - Arithmetic division.<span class="intersentencespace"></span>

  </li>


  <li>
    abs/1 - Returns an integer or float which is the arithmetical absolute value of number.<span class="intersentencespace"></span>

  </li>

</ol>

13.2.5 Miscellaneous functions

<p class="noindent">
  Finally, there are some other interesting miscellaneous functions.<span class="intersentencespace"></span> Here they are with a description for your convenience.
</p>


<ol>
  <li>
    apply/3 - Invokes the given fun from module with the list of arguments.<span class="intersentencespace"></span>

  </li>


  <li>
    function_exported?/3 - Returns true if module is loaded and contains a public function with the given arity, otherwise false.<span class="intersentencespace"></span>

  </li>


  <li>
    macro_exported?/3 - Returns true if module is loaded and contains a public macro with the given arity, otherwise false.<span class="intersentencespace"></span>

  </li>


  <li>
    self/0 - Returns the PID (process identifier) of the calling process.<span class="intersentencespace"></span>

  </li>


  <li>
    make_ref/0 - Returns an almost unique reference.<span class="intersentencespace"></span>

  </li>

</ol>

13.3 Summary

I hope you enjoyed this whirlwind tour of the Kernel module. There’s more functions I didn’t cover, but I wnated to give you a highlight of some of the ones you would likely use in your coding endeavors.

Chapter 14 Digging Into Protocols

14.1 Pattern Matching: When You Have a Hammer Everything Looks Like a Nail

So I was coding a new Elixir hex package in the fall of 2017 called Digger. The whole point of this package was to make it easy to ensure any key in a map was a string (“stringify-ing” map keys) or an atom (“atomizing” keys).

At that time, I was familiar enough with Elixir to avoid abusing the “cond” and “case” statements and to use pattern matching.

In atomizing keys, I wound up with a module like the below. Note there is only one public function called “atomize”. The rest of the functions are private and support the “atomize” function.

The module to convert map keys to strings had an analogous interface.

defmodule Digger.Atomizer do
  @moduledoc """
  Documentation for Digger.Atomizer.
  """

@type key :: any @type value :: any @type pseudo_map :: any

@doc """ Take a (nested) map and convert string and integer keys to atoms """ @spec atomize(map) :: map def atomize(%{} = map) do map |> Map.new(fn{key, value} -> {atomizekey(key), atomizevalue(value)} end) end

defp atomizevalue(value) when ismap(value) do atomize(value) end

defp atomize_value(value), do: value

defp atomizekey(%{} = struct), do: struct

defp atomizekey(key) when ismap(key) do atomize(key) end

defp atomizekey(key) when isbinary(key) do String.to_atom(key) end

defp atomizekey(key) when isinteger(key) do key |> tostring |> atomizekey end

defp atomize_key(key), do: key end

</div>

If you look at the above code, you’ll notice I started using guards to decide how to atomize a key based on the type of data it was. For example, if it was an integer, the “atomize_key” function used the to_string function to convert the key to a string and then called the. For a struct, I actually wouldn’t try and “atomize” it and kept using the struct as the key.

If only there were a mechanism in Elixir so that would let me dynamically call a function depending on a value’s type. This would let me more easily extend this module’s API for newly defined data types.

14.2 Enter Protocols: What Are They?

Before we talk about protocols, we actually have to take a quick detour to talk about polymorphism.

14.2.1 Ok, so what is polymorphism?

<p class="noindent">
  From Wikipedia: “In programming languages and type theory, polymorphism (from Greek πολύς, polys, “many, much” and μορφή, morphē, “form, shape”) is the provision of a single interface to entities of different types.”<sup id="cha-14_footnote-ref-1" class="footnote"><a href="#cha-14_footnote-1">1</a></sup>
</p>


<p>
  More from Wikipedia:
</p>


<ul>
  <li>
    Ad hoc polymorphism: when a function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations.<span class="intersentencespace"></span> Ad hoc polymorphism is supported in many languages using function overloading.<span class="intersentencespace"></span>

  </li>


  <li>
    Parametric polymorphism: when code is written without mention of any specific type and thus can be used transparently with any number of new types.<span class="intersentencespace"></span> In the object-oriented programming community, this is often known as generics or generic programming.<span class="intersentencespace"></span> In the functional programming community, this is often shortened to polymorphism.<span class="intersentencespace"></span>

  </li>


  <li>
    Subtyping (also called subtype polymorphism or inclusion polymorphism): when a name denotes instances of many different classes related by some common superclass.<span class="intersentencespace"></span>

  </li>

</ul>


<p>
  Apparently, according to Wikipedia, Elixir uses parametric polymorphism and the functional programming community just refers to it as “polymorphism.”
</p>


<p>
  Also interestingly enough, while Elixir is a dynamic language, Wikipedia states “parametric polymorphism is a way to make a language more expressive, while still maintaining full static type-safety.”<sup id="cha-14_footnote-ref-2" class="footnote"><a href="#cha-14_footnote-2">2</a></sup>
</p>

14.2.2 Protocols Defined

<p class="noindent">
  So after all that, what are protocols?
</p>


<p>
  The Elixir documentation states “Protocols are a mechanism to achieve polymorphism in Elixir.”<sup id="cha-14_footnote-ref-3" class="footnote"><a href="#cha-14_footnote-3">3</a></sup>
</p>


<p>
  In layman’s terms that means we depend on function arity and the data types passed in to the function to determine which protocol implementation to dispatch.
</p>

14.2.3 Practically speaking, how do you use protocols in Elixir?

<p class="noindent">
  You only need to remember 2 syntax keywords when using when working with polymorphism in Elixir: defprotocol and defimpl.<span class="intersentencespace"></span> As we step through the following case study with the <a href="https://github.com/treble37/digger" target="_blank" rel="noopener">hex package Digger</a>, hopefully it will become more clear.
</p>

14.2.4 A Case Study On Using Polymorphism: Rewriting the Digger.Atomizer Module Using Protocols

<p class="noindent">
  So now let’s step through a small case study by rewriting the Digger.Atomizer module.
</p>

14.2.5 Step 1: Define Your Protocol with defprotocol

<p class="noindent">
  <div class="code">
    <div class="highlight">
      <pre># file: lib/protocols/atomizer_protocol.ex

defprotocol Digger.Atomizer do @moduledoc """ Documentation for Digger.Atomizer Protocol """

@fallbacktoany true

alias Digger.Types

@doc """ ‘Atomize’ a valid Types.data_type according to the protocol implementation """

@spec atomize(Types.datatype, Types.string) :: Types.validreturntype def atomize(datatype, atomize \ :atomize) end

    </div>

  </div>
  </div>


  <div id="uid174" data-tralics-id="uid174" class="subsection" data-number="14.2.6">
    <h3>
      <a href="#uid174" class="heading hyperref"><span class="number">14.2.6 </span>Step 2: Define Your Implementation with defimpl</a>
    </h3>


    <p class="noindent">
      For string keys, here is the implementation of the protocol.
    </p>


    <div class="code">
      <div class="highlight">
        <pre># file: lib/impl/atomizer/string.ex

defimpl Digger.Atomizer, for: BitString do def atomize(string, :atomize) do string |> String.toatom end def atomize(string, \atomize), do: string end

      </div>

    </div>

  </div>


  <div id="uid175" data-tralics-id="uid175" class="subsection" data-number="14.2.7">
    <h3>
      <a href="#uid175" class="heading hyperref"><span class="number">14.2.7 </span>Step 3: Implement Any as a Fallback</a>
    </h3>


    <p class="noindent">
      In the following code example, you’ll notice we define a protocol implementation for “Any”.<span class="intersentencespace"></span> This is to let Elixir know what to do in case it can’t find a function implementation for a particular data type.
    </p>


    <p>
      In the definition of the protocol itself, we also set the @fallback_to_any attribute to true.
    </p>


    <div class="code">
      <div class="highlight">
        <pre># file: lib/impl/atomizer/any.ex

defimpl Digger.Atomizer, for: Any do def atomize(any, _atomize), do: any end

file: lib/protocols/atomizer_protocol.ex

defprotocol Digger.Atomizer do @moduledoc """ Documentation for Digger.Atomizer Protocol """

@fallbacktoany true

alias Digger.Types

@doc """ ‘Atomize’ a valid Types.data_type according to the protocol implementation """

@spec atomize(Types.datatype, Types.string) :: Types.validreturntype def atomize(datatype, atomize \ :atomize) end

      </div>

    </div>


    <p>
      Alternatively, you can use the @derive attribute in a module to tell Elixir to use the “Any” implementation for that module.
    </p>


    <p>
      What if the implementation of Digger.Atomizer.Protocol had not been applicable to any data type?
    </p>


    <p>
      From the <a href="http://elixir-lang.github.io/getting-started/protocols.html#fallback-to-any" target="_blank" rel="noopener">Elixir documentation</a>:
    </p>


    <blockquote class="quotation">
      <p class="quote">
        “That’s one of the reasons why @fallback_to_any is an opt-in behaviour.<span class="intersentencespace"></span> For the majority of protocols, raising an error when a protocol is not implemented is the proper behaviour.”<span class="intersentencespace"></span> “Which technique is best between deriving and falling back to any depends on the use case but, given Elixir developers prefer explicit over implicit, you may see many libraries pushing towards the @derive approach.”<span class="intersentencespace"></span>
      </p>

    </blockquote>

  </div>
  </div>


  <div id="cid63" data-tralics-id="cid63" class="section" data-number="14.3">
    <h2>
      <a href="#cid63" class="heading hyperref"><span class="number">14.3 </span>Best practices for organizing protocols and their implementation?</a>
    </h2>


    <ul>
      <li>
        Apparently, it’s still an <a href="https://github.com/christopheradams/elixir_style_guide/issues/84" target="_blank" rel="noopener">open issue as of 1/15/18 Monday</a>

      </li>

    </ul>

  </div>


  <div id="cid64" data-tralics-id="cid64" class="section" data-number="14.4">
    <h2>
      <a href="#cid64" class="heading hyperref"><span class="number">14.4 </span>Other Tips</a>
    </h2>


    <ul>
      <li>
        <a href="https://medium.com/everydayhero-engineering/extensibility-in-elixir-using-protocols-2e8fb0a35c48" target="_blank" rel="noopener">According to this blog post</a>, a protocol implementation can use the @for module attribute as an alias of the current target.<span class="intersentencespace"></span> It’s handy for different protocol implementations.<span class="intersentencespace"></span>

      </li>

    </ul>


    <p class="noindent">
      <div class="code">
        <div class="highlight">
          <pre>defprotocol ToString do

def tostring(term) end defimpl ToString, for: [List, Integer] do def tostring(term) do @for.tostring(term) end end ToString.tostring(2)

=> “2”

        </div>

      </div>
      </div>


      <div id="cid65" data-tralics-id="cid65" class="section" data-number="14.5">
        <h2>
          <a href="#cid65" class="heading hyperref"><span class="number">14.5 </span>Summary</a>
        </h2>


        <p class="noindent">
          Consider using protocols when you find yourself writing functions whose implementation soley depends on the data type(s) being passed in.
        </p>

      </div>


      <div id="cid66" data-tralics-id="cid66" class="section" data-number="14.6">
        <h2>
          <a href="#cid66" class="heading hyperref"><span class="number">14.6 </span>Resources:</a>
        </h2>


        <ol>
          <li>
            <a href="https://stackoverflow.com/questions/4969593/achieving-polymorphism-in-functional-programming" target="_blank" rel="noopener">More reading on questions about approaching polymorphism in functional programming</a>

          </li>


          <li>
            <a href="https://stackoverflow.com/questions/1031273/what-is-polymorphism-what-is-it-for-and-how-is-it-used" target="_blank" rel="noopener">Some general reading on polymorphism in object-oriented programming</a>

          </li>

        </ol>

      </div>


      <div id="cid67" data-tralics-id="cid67" class="section" data-number="14.7">
        <h2>
          <a href="#cid67" class="heading hyperref"><span class="number">14.7 </span>Footnotes:</a>
        </h2>

      </div>


      <div id="cha-14_footnotes">
        <ol class="footnotes">
          <li id="cha-14_footnote-1">
            <a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)" target="_blank" rel="noopener">Polymorphism (computer science)</a> <a class="arrow" href="#cha-14_footnote-ref-1">↑</a>
          </li>


          <li id="cha-14_footnote-2">
            <a href="https://en.wikipedia.org/wiki/Parametric_polymorphism" target="_blank" rel="noopener">Parametric polymorphism</a> <a class="arrow" href="#cha-14_footnote-ref-2">↑</a>
          </li>


          <li id="cha-14_footnote-3">
            <a href="http://elixir-lang.github.io/getting-started/protocols.html" target="_blank" rel="noopener">Documentation of protocols</a> <a class="arrow" href="#cha-14_footnote-ref-3">↑</a>
          </li>

        </ol>

      </div>


      <div id="cid68" data-tralics-id="cid68" class="chapter" data-number="15">
        <h1>
          <a href="#cid68" class="heading hyperref"><span class="number">Chapter 15 </span>Behaviors and Protocols</a>
        </h1>


        <p class="noindent">
          One thing I’ve always loved is efficiency.<span class="intersentencespace"></span> I love checklists and templates so I don’t have to think about repeatable processes.<span class="intersentencespace"></span> Templates can help keep you really organized.<span class="intersentencespace"></span> When I did some freelancing, I had a contract template that I could edit to quickly make changes.<span class="intersentencespace"></span> It saved a ton of time.
        </p>

      </div>


      <div id="cid69" data-tralics-id="cid69" class="section" data-number="15.1">
        <h2>
          <a href="#cid69" class="heading hyperref"><span class="number">15.1 </span>And what does this have to do with behaviors?</a>
        </h2>


        <p class="noindent">
          In an analogous fashion to the contracting templates I used to use, Elixir defines behaviors for modules.<span class="intersentencespace"></span> Behaviors let you define a module and specify what functions must be a part of the module.
        </p>

      </div>


      <div id="cid70" data-tralics-id="cid70" class="section" data-number="15.2">
        <h2>
          <a href="#cid70" class="heading hyperref"><span class="number">15.2 </span>Defining Behaviors</a>
        </h2>


        <p class="noindent">
          The way to define a behavior is through a “@behaviour” attribute.<span class="intersentencespace"></span> The module whose “behavior” you are implementing must use the @callback attribute to define the functions that are part of the contract it will enforce to all modules that wish to use its “behavior”.
        </p>


        <div id="uid180" data-tralics-id="uid180" class="subsection" data-number="15.2.1">
          <h3>
            <a href="#uid180" class="heading hyperref"><span class="number">15.2.1 </span>In coded English, a behavior does the following</a>
          </h3>


          <p class="noindent">
            <div class="code">
              <div class="highlight">
                <pre>defmodule Hello do

@callback hello(name :: bitstring())::bitstring() end

defmodule Hello.FirstName do @behaviour Hello

def hello(name), do: IO.puts “hello #{name}!” end

              </div>

            </div>
            </div>


            <div id="uid181" data-tralics-id="uid181" class="subsection" data-number="15.2.2">
              <h3>
                <a href="#uid181" class="heading hyperref"><span class="number">15.2.2 </span>Use the @callback attribute to specify the functions that are part of the @behavior contract</a>
              </h3>


              <p class="noindent">
                The @callback attribute in the example above tells Elixir that the “hello” function that takes a bitstring argument must be part of any module that wishes to implement the Hello module behavior.
              </p>


              <p>
                What happens if you fail to implement the method specified by callback?
              </p>


              <p>
                I experimented in the iex shell and found I got a warning:
              </p>


              <div class="code">
                <div class="highlight">
                  <pre>warning: function hello/1 required by behaviour Hello is not implemented (in module Hello.FirstName)

iex:4

                </div>

              </div>


              <p>
                So no one will revoke your license to program, but it looks like not including the contractualy specified behavior is frowned upon.
              </p>

            </div>
            </div>


            <div id="cid71" data-tralics-id="cid71" class="section" data-number="15.3">
              <h2>
                <a href="#cid71" class="heading hyperref"><span class="number">15.3 </span>Dynamic Dispatching</a>
              </h2>


              <p class="noindent">
                One interesting thing you can do with behaviors is dynamically dispatching to a specific implementation.<span class="intersentencespace"></span> Let me give you a quick and contrived example.
              </p>


              <div class="code">
                <div class="highlight">
                  <pre>defmodule Hello do

@callback hello(name :: bitstring())::bitstring()

def hellogeneral!(implementation, name \ "") do hellomessage = implementation.hello(name) ”#{hello_message} You are a General.” end end

defmodule Hello.FirstName do @behaviour Hello

def hello(name), do: “hello #{name}!” end

defmodule Hello.RandomNumber do @behavior Hello def hello(name), do: “hello #{name}, your lucky number is #{:rand.uniform(100)}” end

                </div>

              </div>


              <p>
                Below is some sample output from an iex shell:
              </p>


              <div class="code">
                <div class="highlight">
                  <pre>iex(15)> Hello.hello_general!(Hello.FirstName, "Smith")

“hello Smith! You are a General.”

iex(16)> Hello.hello_general!(Hello.RandomNumber, “Murphy”) “hello Murphy, your lucky number is 76 You are a General.”

                </div>

              </div>


              <p>
                Notice how easy it is to dynamically dispatch based on a module.
              </p>

            </div>


            <div id="cid72" data-tralics-id="cid72" class="section" data-number="15.4">
              <h2>
                <a href="#cid72" class="heading hyperref"><span class="number">15.4 </span>Relation to Protocols</a>
              </h2>


              <p class="noindent">
                The following table I pulled from a blog post by a man named Samuel D.<sup id="cha-15_footnote-ref-1" class="footnote intersentence"><a href="#cha-15_footnote-1">1</a></sup><span class="intersentencespace"></span> It gives a nice comparison between protocols and behaviors.
              </p>


              <table class="tabular">
                <tr class="top_border bottom_border">
                  <td class="left_border align_left right_border">
                    Protocols
                  </td>


                  <td class="align_left right_border">
                    Behaviors
                  </td>

                </tr>


                <tr>
                  <td class="left_border align_left right_border">
                    Apply to data structures
                  </td>


                  <td class="align_left right_border">
                    Apply to modules
                  </td>

                </tr>


                <tr>
                  <td class="left_border align_left right_border">
                    Specify new implementations of existing functions for new datatypes
                  </td>


                  <td class="align_left right_border">
                    Specify a public spec/contract for modules to implement
                  </td>

                </tr>


                <tr>
                  <td class="left_border align_left right_border">
                    “Here’s my datatype, it can X”
                  </td>


                  <td class="align_left right_border">
                    “Here’s my module, it implements Y”
                  </td>

                </tr>


                <tr class="bottom_border">
                  <td class="left_border align_left right_border">
                    Exclusive to Elixir
                  </td>


                  <td class="align_left right_border">
                    Provided by the Erlang runtime
                  </td>

                </tr>

              </table>


              <p>
                The main idea is that protocols can be thought of as “template” functions for handling different data types while behaviors can be thought of as “template” contracts that tell modules what functions to implement.
              </p>

            </div>


            <div id="cid73" data-tralics-id="cid73" class="section" data-number="15.5">
              <h2>
                <a href="#cid73" class="heading hyperref"><span class="number">15.5 </span>Summary</a>
              </h2>


              <p class="noindent">
                Elixir behaviors can be a great tool for helping to organize your code by specifying contracts and keeping your coding intentions clear.
              </p>


              <div id="uid183" data-tralics-id="uid183" class="subsection" data-number="15.5.1">
                <h3>
                  <a href="#uid183" class="heading hyperref"><span class="number">15.5.1 </span>Footnotes</a>
                </h3>

              </div>

            </div>


            <div id="cha-15_footnotes">
              <ol class="footnotes">
                <li id="cha-15_footnote-1">
                  <a href="http://samueldavies.net/2017/04/19/polymorphism-in-elixir-protocols-vs-behaviours/" target="_blank" rel="noopener">Source: http://samueldavies.net/2017/04/19/polymorphism-in-elixir-protocols-vs-behaviours/</a> <a class="arrow" href="#cha-15_footnote-ref-1">↑</a>
                </li>

              </ol>


              <p>
                <a href='https://binarywebpark.clickfunnels.com/optinsurvey8kfrv6j4' target='_blank'><img src="http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px.png" alt="" width="800" height="800" class="alignnone size-full wp-image-1722" srcset="http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px.png 800w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-150x150.png 150w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-300x300.png 300w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-768x768.png 768w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-550x550.png 550w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-500x500.png 500w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-225x225.png 225w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-200x200.png 200w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-400x400.png 400w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-260x260.png 260w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-600x600.png 600w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-414x414.png 414w, http://www.binarywebpark.com/wp-content/uploads/2017/10/learn_elixir_beta_cta_blog800px-266x266.png 266w" sizes="(max-width: 800px) 100vw, 800px" /></a>
              </p>

            </div>


            <div id="cid74" data-tralics-id="cid74" class="chapter" data-number="16">
              <h1>
                <a href="#cid74" class="heading hyperref"><span class="number">Chapter 16 </span>Guards</a>
              </h1>


              <p class="noindent">
                Sometimes I’ve found myself wanting to only call a certain function depending on a certain condition.<span class="intersentencespace"></span> For example, I might only want to call a function when one of the parameters is greater than the other.
              </p>


              <p>
                I did this in a production Phoenix application recently when I was trying to recursively generate a routing path
              </p>

            </div>


            <div id="cid75" data-tralics-id="cid75" class="section" data-number="16.1">
              <h2>
                <a href="#cid75" class="heading hyperref"><span class="number">16.1 </span>What is a guard?</a>
              </h2>


              <p class="noindent">
                Elixir guards are special little clauses denoted with the keyword <em>when</em> that are used to apply extra checks on pattern matched functions.
              </p>


              <p>
                Here’s a quick concrete code snippet:
              </p>


              <div class="code">
                <div class="highlight">
                  <pre>def generate_path(path, j, k) when k > j and is_integer(j) and is_integer(k), do: path
                </div>

              </div>


              <p>
                So in the above snippet, this function will only be called when the condition “k > j” is met and they are both integers.
              </p>

            </div>


            <div id="cid76" data-tralics-id="cid76" class="section" data-number="16.2">
              <h2>
                <a href="#cid76" class="heading hyperref"><span class="number">16.2 </span>Why Use a Guard?</a>
              </h2>


              <p class="noindent">
                Like I said before, I found myself reaching for guard clauses when I want to apply a check on the parameters I pass into a function.
              </p>

            </div>


            <div id="cid77" data-tralics-id="cid77" class="section" data-number="16.3">
              <h2>
                <a href="#cid77" class="heading hyperref"><span class="number">16.3 </span>Types of Functions You Can Use With Guards</a>
              </h2>


              <p class="noindent">
                So remember in <a href="#cha-chapter_kernels" class="hyperref">Chapter <span class="ref">13</span></a> A Tour of Kernels, we described the <em>is_</em> functions like is_integer, is_atom, and so on?<span class="intersentencespace"></span> Also, do you recall the <em>data structure functions</em> such as byte_size, map_size, and so on?
              </p>


              <p>
                Well those are the functions that are allowed in guards.<span class="intersentencespace"></span> The complete list is documented in the <a href="https://hexdocs.pm/elixir/guards.html" target="_blank" rel="noopener">documentation</a>.
              </p>

            </div>


            <div id="cid78" data-tralics-id="cid78" class="section" data-number="16.4">
              <h2>
                <a href="#cid78" class="heading hyperref"><span class="number">16.4 </span>Why You Can’t Use Custom Functions with Guards</a>
              </h2>


              <table class="tabular">
                <tr class="top_border bottom_border">
                  <td class="left_border align_left right_border">
                    You can also use the typical logical operators like &&,
                  </td>


                  <td class="align_left right_border">

                  </td>


                  <td class="align_left right_border">
                    , and !.
                  </td>

                </tr>

              </table>


              <p class="noindent">
                For convenience, I’ll quote from the documenation below.
              </p>


              <div id="uid184" data-tralics-id="uid184" class="subsection" data-number="16.4.1">
                <h3>
                  <a href="#uid184" class="heading hyperref"><span class="number">16.4.1 </span>Operators and Functions You Can Use in Guards</a>
                </h3>


                <div id="uid185" data-tralics-id="uid185" class="subsubsection" data-number="16.4.1.1">
                  <h4>
                    <a href="#uid185" class="heading">Operators</a>
                  </h4>


                  <blockquote class="quotation">
                    <p class="quote noindent noindent">
                      comparison operators (==, !=, ===, !==, >, >=, <, <=)
                      strictly boolean operators (and, or, not) (the &&, ||, and !<span class="intersentencespace"></span> sibling operators are not allowed as they’re not strictly boolean - meaning they don’t require both sides to be booleans)<br />
                      arithmetic binary operators (+, -, *, /)<br />
                      arithmetic unary operators (+, -)<br />
                      binary concatenation operator (<>)<br />
                      in and not in operators (as long as the right-hand side is a list or a range)
                    </p>

                  </blockquote>

                </div>


                <div id="uid186" data-tralics-id="uid186" class="subsubsection" data-number="16.4.1.2">
                  <h4>
                    <a href="#uid186" class="heading">Functions</a>
                  </h4>


                  <p class="noindent">
                    Below are the built-in Elixir functions you can use with guards.
                  </p>


                  <div class="code">
                    <div class="highlight">
                      <pre>is_atom/1

isbinary/1 isbitstring/1 isboolean/1 isfloat/1 isfunction/1 isfunction/2 isinteger/1 islist/1 ismap/1 isnil/1 isnumber/1 ispid/1 isport/1 isreference/1 is_tuple/1

                    </div>

                  </div>


                  <div class="code">
                    <div class="highlight">
                      <pre>abs/1

binarypart/3 bitsize/1 bytesize/1 div/2 elem/2 hd/1 length/1 mapsize/1 node/0 node/1 rem/2 round/1 self/0 tl/1 trunc/1 tuple_size/1

                    </div>

                  </div>


                  <p>
                    The documentation is a quick read that shows you all the details, and I encourage you to give it a read if you’re able.
                  </p>

                </div>

              </div>


              <div id="uid187" data-tralics-id="uid187" class="subsection" data-number="16.4.2">
                <h3>
                  <a href="#uid187" class="heading hyperref"><span class="number">16.4.2 </span>Why You Can’t Use Custom Functions With Guards</a>
                </h3>


                <p class="noindent">
                  Once I tried using my custom function as a guard clause.<span class="intersentencespace"></span> It didn’t work.
                </p>


                <p>
                  Why?
                </p>


                <p>
                  With the way Erlang executes functions, each function is tested from top to bottom of the code.<span class="intersentencespace"></span> If a guard clause were allowed to have a side effect, then you couldn’t guarantee functional purity.
                </p>


                <p>
                  To ensure that guard clause functions have no side effects (i.e., “pure functions”) and executed quickly, this blog post by Chris Keathley<sup id="cha-16_footnote-ref-1" class="footnote"><a href="#cha-16_footnote-1">1</a></sup> stated that Erlang’s authors decided to limit guard clause functions to Erlang’s built-in functions.
                </p>

              </div>


              <div id="uid189" data-tralics-id="uid189" class="subsection" data-number="16.4.3">
                <h3>
                  <a href="#uid189" class="heading hyperref"><span class="number">16.4.3 </span>Or Can You Use Custom Functions?</a>
                </h3>


                <p class="noindent">
                  Sort of.<span class="intersentencespace"></span> You can define your own guards using Elixir macros.<span class="intersentencespace"></span> However, you still must use Elixir’s built-in functions and operators for the guards to be valid.
                </p>


                <div id="uid190" data-tralics-id="uid190" class="subsubsection" data-number="16.4.3.1">
                  <h4>
                    <a href="#uid190" class="heading">Example Macro Guard</a>
                  </h4>


                  <p class="noindent">
                    <div class="code">
                      <div class="highlight">
                        <pre>defmodule Hello do

defmacro islessthan(m, n) do quote do: unquote(m) < unquote(n) end end defmodule World do import Hello def outputnumbers(m, n) when islessthan(m, n), do: “Hello #{m} #{n}” def outputnumbers(m, n), do: “Hello without numbers” end

                      </div>

                    </div>
                    </div>
                    </div>


                    <div id="uid191" data-tralics-id="uid191" class="subsection" data-number="16.4.4">
                      <h3>
                        <a href="#uid191" class="heading hyperref"><span class="number">16.4.4 </span>Introducing defguard(p) in Elixir 1.6</a>
                      </h3>


                      <p class="noindent">
                        As of Elixir 1.6<sup id="cha-16_footnote-ref-2" class="footnote"><a href="#cha-16_footnote-2">2</a></sup>, you now have defguard/1 (or defguardp/1) to define guard macros.<span class="intersentencespace"></span> This helps you avoid unnecessarily complicated metaprogramming voodoo depending on whether or not the function is being invoked in a guard or not as described in this <a href="https://github.com/elixir-lang/elixir/issues/2469" target="_blank" rel="noopener">github issue</a>.
                      </p>

                    </div>
                    </div>


                    <div id="cid79" data-tralics-id="cid79" class="section" data-number="16.5">
                      <h2>
                        <a href="#cid79" class="heading hyperref"><span class="number">16.5 </span>Summary</a>
                      </h2>


                      <p class="noindent">
                        Overall, I’ve found guard clauses to be useful, especially when I need to quickly apply a conditional check on function parameters.
                      </p>

                    </div>


                    <div id="cha-16_footnotes">
                      <ol class="footnotes">
                        <li id="cha-16_footnote-1">
                          <a href="https://keathley.io/2016/04/09/elixir-guard-clauses.html" target="_blank" rel="noopener">Source: Using Functions in Elixir Guard Clauses</a> <a class="arrow" href="#cha-16_footnote-ref-1">↑</a>
                        </li>


                        <li id="cha-16_footnote-2">
                          <a href="https://elixir-lang.org/blog/2018/01/17/elixir-v1-6-0-released/" target="_blank" rel="noopener">Source: Elixir v1.6 released</a> <a class="arrow" href="#cha-16_footnote-ref-2">↑</a>
                        </li>

                      </ol>

                    </div>


                    <div id="cid80" data-tralics-id="cid80" class="chapter" data-number="17">
                      <h1>
                        <a href="#cid80" class="heading hyperref"><span class="number">Chapter 17 </span>IO and Files</a>
                      </h1>


                      <p class="noindent">
                        Not too long ago I was working on modifying an endpoint in a Phoenix web application that allowed you to upload a CSV file and insert that data into a database table.
                      </p>


                      <p>
                        In that code I noticed a reference to <em>File.stream!</em>.<span class="intersentencespace"></span> And so I began digging further.
                      </p>

                    </div>


                    <div id="cid81" data-tralics-id="cid81" class="section" data-number="17.1">
                      <h2>
                        <a href="#cid81" class="heading hyperref"><span class="number">17.1 </span>File Module and Functions</a>
                      </h2>


                      <p class="noindent">
                        There’s a bit of interplay between the File and IO modules in Elixir.<span class="intersentencespace"></span> Since files are opened in binary mode by default, developers have to use IO.binwrite/2 and IO.binread/2 functions when reading and writing files.
                      </p>


                      <p>
                        If you want to tell Elixir to to interpret a file as utf8, you can open it with the :utf8 encoding option.
                      </p>


                      <div id="uid193" data-tralics-id="uid193" class="subsection" data-number="17.1.1">
                        <h3>
                          <a href="#uid193" class="heading hyperref"><span class="number">17.1.1 </span>Bang and Non-Bang Function API</a>
                        </h3>


                        <p class="noindent">
                          The bang file methods (denoted with a !<span class="intersentencespace"></span> after the method name) typically raise an error on failure and return :ok on success.
                        </p>


                        <p>
                          The non-bang functions typically return an error tuple on failure and return :ok on success.
                        </p>

                      </div>


                      <div id="uid194" data-tralics-id="uid194" class="subsection" data-number="17.1.2">
                        <h3>
                          <a href="#uid194" class="heading hyperref"><span class="number">17.1.2 </span>File Function Examples</a>
                        </h3>


                        <p class="noindent">
                          So let’s take a look at some basic file functions.<span class="intersentencespace"></span> You’ll notice quite a few of the functions in the File module are named after their Unix/Linux cousins.
                        </p>


                        <div id="uid195" data-tralics-id="uid195" class="subsubsection" data-number="17.1.2.1">
                          <h4>
                            <a href="#uid195" class="heading">cd/1</a>
                          </h4>


                          <p class="noindent">
                            Below I set the current working directory.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex> File.cd("/Users/bruce")

:ok

                            </div>

                          </div>

                        </div>


                        <div id="uid196" data-tralics-id="uid196" class="subsubsection" data-number="17.1.2.2">
                          <h4>
                            <a href="#uid196" class="heading">stat/2</a>
                          </h4>


                          <p class="noindent">
                            Next, I get some stats on a file I created in /Users/bruce.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(5)> File.stat("toss.txt")

{:ok, %File.Stat{ access: :readwrite, atime: {{2018, 2, 14}, {17, 49, 50}}, ctime: {{2018, 2, 14}, {17, 49, 50}}, gid: 20, inode: 18691495, links: 1, majordevice: 16777218, minor_device: 0, mode: 33188, mtime: {{2018, 2, 14}, {17, 49, 50}}, size: 6, type: :regular, uid: 501 }}

                            </div>

                          </div>


                          <p>
                            atime indicates the last time the file was read.<span class="intersentencespace"></span> For Unix systems, ctime is the last time the file or inode was changed.<span class="intersentencespace"></span> In Windows, it is the time of creation.<span class="intersentencespace"></span> The links field indicates the number of links to the file.<span class="intersentencespace"></span> The size field gives the size of the file in bytes.
                          </p>

                        </div>


                        <div id="uid197" data-tralics-id="uid197" class="subsubsection" data-number="17.1.2.3">
                          <h4>
                            <a href="#uid197" class="heading">chmod/2</a>
                          </h4>


                          <p class="noindent">
                            Similar to the analagous Unix command, you can change file permissions.<span class="intersentencespace"></span> The only difference is you use octal flags.
                          </p>


                          <p>
                            Below is an example.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(1)> File.chmod("toss2.txt", 0o040)

:ok

these are the permissions before calling File.chmod…

-rw-r—r— 1 bru staff 6 Feb 14 19:59 toss2.txt

these are the permissions after calling File.chmod…

----r----- 1 bru staff 6 Feb 14 20:05 toss2.txt

                            </div>

                          </div>


                          <p>
                            Here are the flags reprinted from the <a href="https://hexdocs.pm/elixir/File.html#chmod/2" target="_blank" rel="noopener">documentation for your convenience</a>.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>0o400 - read permission: owner

0o200 - write permission: owner 0o100 - execute permission: owner 0o040 - read permission: group 0o020 - write permission: group 0o010 - execute permission: group 0o004 - read permission: other 0o002 - write permission: other 0o001 - execute permission: other

                            </div>

                          </div>

                        </div>


                        <div id="uid198" data-tralics-id="uid198" class="subsubsection" data-number="17.1.2.4">
                          <h4>
                            <a href="#uid198" class="heading">dir?</a>
                          </h4>


                          <p class="noindent">
                            This handy method lets you inquire if a file is a directory.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex> File.dir?("toss.txt")

false

                            </div>

                          </div>

                        </div>


                        <div id="uid199" data-tralics-id="uid199" class="subsubsection" data-number="17.1.2.5">
                          <h4>
                            <a href="#uid199" class="heading">exists?</a>
                          </h4>


                          <p class="noindent">
                            You can figure out if the path (or file) exists.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(3)> File.exists?("toss.txt")

true

                            </div>

                          </div>

                        </div>


                        <div id="uid200" data-tralics-id="uid200" class="subsubsection" data-number="17.1.2.6">
                          <h4>
                            <a href="#uid200" class="heading">read/1</a>
                          </h4>


                          <p class="noindent">
                            On success, the read/1 function returns a tuple with a status and binary data object that contains the contents of the file.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(5)> File.read("toss.txt")

{:ok, “hello\n”}

                            </div>

                          </div>

                        </div>


                        <div id="uid201" data-tralics-id="uid201" class="subsubsection" data-number="17.1.2.7">
                          <h4>
                            <a href="#uid201" class="heading">rename/2</a>
                          </h4>


                          <p class="noindent">
                            You can also rename files.<span class="intersentencespace"></span> :ok is returned on success, otherwise {:error, reason} where reason is the reason for the error.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(7)> File.rename("toss2.txt", "toss3.txt")

:ok

                            </div>

                          </div>

                        </div>


                        <div id="uid202" data-tralics-id="uid202" class="subsubsection" data-number="17.1.2.8">
                          <h4>
                            <a href="#uid202" class="heading">regular?</a>
                          </h4>


                          <p class="noindent">
                            This function checks if a file is “regular”.<span class="intersentencespace"></span> In layman’s terms this means it checks to see if it’s an executable, a file containing ASCII text, zip file, etc.
                          </p>


                          <p>
                            You can check on your command line for regularity of a file with:
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>$ test -f .vimrc && echo regular

regular

                            </div>

                          </div>


                          <p>
                            As you can see, my .vimrc file is a regular file.
                          </p>


                          <p>
                            In an Elixir iex shell, you can do:
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(13)> File.regular?("/Users/bruce")

false iex(14)> File.regular?(“.vimrc”) true

                            </div>

                          </div>


                          <p>
                            Note that directories in Unix and Linux are “binary files” that locate other files and directories.
                          </p>

                        </div>


                        <div id="uid203" data-tralics-id="uid203" class="subsubsection" data-number="17.1.2.9">
                          <h4>
                            <a href="#uid203" class="heading">write/3</a>
                          </h4>


                          <p class="noindent">
                            And of course, no File module would be complete without a write function.<span class="intersentencespace"></span> Below I wrote the word “hello” out to a file called “toss2.txt”.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(15)> File.write("toss2.txt", "hello", [:write])

:ok

                            </div>

                          </div>


                          <p>
                            There are different modes which are <a href="https://hexdocs.pm/elixir/File.html#open/2" target="_blank" rel="noopener">documented here</a> in the File.open/2 method.
                          </p>

                        </div>

                      </div>

                    </div>


                    <div id="cid82" data-tralics-id="cid82" class="section" data-number="17.2">
                      <h2>
                        <a href="#cid82" class="heading hyperref"><span class="number">17.2 </span>Path Module</a>
                      </h2>


                      <p class="noindent">
                        If you look at the File documentation, you’ll notice it typically takes paths as arguments.<span class="intersentencespace"></span> So I am jotting down some notes about some useful Path functions I found from reading the documentation.
                      </p>


                      <div id="uid204" data-tralics-id="uid204" class="subsection" data-number="17.2.1">
                        <h3>
                          <a href="#uid204" class="heading hyperref"><span class="number">17.2.1 </span>Path Function Examples</a>
                        </h3>


                        <div id="uid205" data-tralics-id="uid205" class="subsubsection" data-number="17.2.1.1">
                          <h4>
                            <a href="#uid205" class="heading">absname/1</a>
                          </h4>


                          <p class="noindent">
                            This handy function converts the path passed in to an absolute path name.<span class="intersentencespace"></span> For example:
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(2)> Path.absname("toss.txt")

“/Users/bruce/toss.txt”

                            </div>

                          </div>

                        </div>


                        <div id="uid206" data-tralics-id="uid206" class="subsubsection" data-number="17.2.1.2">
                          <h4>
                            <a href="#uid206" class="heading">basename/1</a>
                          </h4>


                          <p class="noindent">
                            The basename function returns the last component of the path, whether it’s a file name or folder, or the path if there are no directory separators.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(4)> Path.basename("/Users/bruce/toss.txt")

“toss.txt

                            </div>

                          </div>

                        </div>


                        <div id="uid207" data-tralics-id="uid207" class="subsubsection" data-number="17.2.1.3">
                          <h4>
                            <a href="#uid207" class="heading">dirname/1</a>
                          </h4>


                          <p class="noindent">
                            If a path contains a file name, dirname/1 returns the directory component.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(8)> Path.dirname("/Users/bruce/toss.txt")

“/Users/bruce”

                            </div>

                          </div>

                        </div>


                        <div id="uid208" data-tralics-id="uid208" class="subsubsection" data-number="17.2.1.4">
                          <h4>
                            <a href="#uid208" class="heading">join/1</a>
                          </h4>


                          <p class="noindent">
                            This function takes a list of paths and joins them together, removing any trailing slash on the join.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(1)> Path.join(["~", "toss.txt"])

”~/toss.txt”

                            </div>

                          </div>

                        </div>


                        <div id="uid209" data-tralics-id="uid209" class="subsubsection" data-number="17.2.1.5">
                          <h4>
                            <a href="#uid209" class="heading">wildcard/2</a>
                          </h4>


                          <p class="noindent">
                            One interesting function I found was the wildcard/2 function.<span class="intersentencespace"></span> It traverses paths according to the “glob” expression passed and the wildchard characters passed as options.
                          </p>


                          <p>
                            Here are the special characters <a href="https://hexdocs.pm/elixir/Path.html#wildcard/2" target="_blank" rel="noopener">from the documentation</a>
                          </p>


                          <blockquote class="quotation">
                            <p class="quote">
                              ?<span class="intersentencespace"></span> - matches one character<br />
                              * - matches any number of characters up to the end of the filename, the next dot, or the next slash<br />
                              ** - two adjacent *’s used as a single pattern will match all files and zero or more directories and subdirectories<br />
                              [char1,char2,…] - matches any of the characters listed; two characters separated by a hyphen will match a range of characters.<span class="intersentencespace"></span> Do not add spaces before and after the comma as it would then match paths containing the space character itself.<span class="intersentencespace"></span> {item1,item2,…} - matches one of the alternatives Do not add spaces before and after the comma as it would then match paths containing the space character itself.<span class="intersentencespace"></span>
                            </p>

                          </blockquote>

                        </div>

                      </div>

                    </div>


                    <div id="cid83" data-tralics-id="cid83" class="section" data-number="17.3">
                      <h2>
                        <a href="#cid83" class="heading hyperref"><span class="number">17.3 </span>IO Module and Functions</a>
                      </h2>


                      <p class="noindent">
                        I’ve found myself using the IO module when doing basic debugging when I first started learning Elixir.<span class="intersentencespace"></span> Namely, I was using IO.puts/2 and IO.inspect/2.
                      </p>


                      <div id="uid210" data-tralics-id="uid210" class="subsection" data-number="17.3.1">
                        <h3>
                          <a href="#uid210" class="heading hyperref"><span class="number">17.3.1 </span>IO Function Examples</a>
                        </h3>


                        <p class="noindent">
                          But there are also some other handy IO functions.
                        </p>


                        <div id="uid211" data-tralics-id="uid211" class="subsubsection" data-number="17.3.1.1">
                          <h4>
                            <a href="#uid211" class="heading">binread/2</a>
                          </h4>


                          <p class="noindent">
                            binread/2 lets you read from a “device”.<span class="intersentencespace"></span> If you look at the documentation, this ends up being an atom or pid (process id).
                          </p>


                          <p>
                            In the example, I read from standard input and pass in the :line option.<span class="intersentencespace"></span> This lets binread/2 know how to iterate through the device (e.g., line by line or a certain number of bytes).
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(1)> IO.binread(:stdio, :line)

Hello “Hello\n”

                            </div>

                          </div>

                        </div>


                        <div id="uid212" data-tralics-id="uid212" class="subsubsection" data-number="17.3.1.2">
                          <h4>
                            <a href="#uid212" class="heading">gets/2</a>
                          </h4>


                          <p class="noindent">
                            gets/2 lets you read one line from an IO device.<span class="intersentencespace"></span> :stdio is the default device.
                          </p>


                          <p>
                            In the below example, I specify :stdio to show you the argument parameter, though I didn’t actually need to.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(5)> IO.gets(:stdio, "What's your name?\n")

What’s your name? Bruce “Bruce\n”

                            </div>

                          </div>

                        </div>


                        <div id="uid213" data-tralics-id="uid213" class="subsubsection" data-number="17.3.1.3">
                          <h4>
                            <a href="#uid213" class="heading">puts/2</a>
                          </h4>


                          <p class="noindent">
                            When I started with Elixir, the first thing I used to debug code was IO.puts/2.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(7)> IO.puts :stdio, "hello"

hello :ok

                            </div>

                          </div>


                          <p>
                            puts/2 writes an item to a device (the default is :stdio) and adds a newline at the end.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(1)> m = %{a: 1, b: 2}

%{a: 1, b: 2} iex(2)> IO.puts m ** (Protocol.UndefinedError) protocol String.Chars not implemented for %{a: 1, b: 2} (elixir) lib/string/chars.ex:3: String.Chars.implfor!/1 (elixir) lib/string/chars.ex:22: String.Chars.tostring/1 (elixir) lib/io.ex:553: IO.puts/2

                            </div>

                          </div>


                          <p>
                            As you can see from the error above, puts/2 will not work with maps (or tuples).
                          </p>

                        </div>


                        <div id="uid214" data-tralics-id="uid214" class="subsubsection" data-number="17.3.1.4">
                          <h4>
                            <a href="#uid214" class="heading">inspect/2</a>
                          </h4>


                          <p class="noindent">
                            Fortunately, Elixir also has inspect/2 which can be useful for debugging.<span class="intersentencespace"></span> inspect/2 doesn’t change the argument passed in but returns it unchanged.<span class="intersentencespace"></span> So you can use it in your code to get a peak at raw values, including maps and tuples (and other pieces of data where IO.puts/2 will throw an error).
                          </p>
                          <div3 id="uid215" data-tralics-id="uid215" data-number="">A Word on Inspect.Opts for Debugging</p>


                          <p>
                            You’ll notice in the following example Elixir treats the list of integers as ASCII codes and outputs their letter representation.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(8)> t=[97, 98, 99]

‘abc’ iex(9)> IO.inspect t ‘abc’ ‘abc’

                            </div>

                          </div>


                          <p>
                            To avoid, this you can turn to the Inspect.Opts module which defines the options used by inspect.<span class="intersentencespace"></span> To print out numbers, you can pass the :as_lists option as seen below.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(10)> IO.inspect t, [charlists: :as_lists]

[97, 98, 99] ‘abc’

                            </div>

                          </div>


                          <p>
                            You can review the other <a href="https://hexdocs.pm/elixir/Inspect.Opts.html" target="_blank" rel="noopener">options</a>, but one of the most useful ones I’ve found is the ability to print out a non-truncated list.<span class="intersentencespace"></span> In the example below you can see I use the :infinity option to see the whole list of numbers from 1 to 100.
                          </p>


                          <p>
                            Together with :as_lists, this should make your early debugging life much easier.
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>iex(16)> b = Enum.to_list 1..100

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, …] iex(17)> IO.inspect b, [limit: :infinity][1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, …]

write/2

write/2 allows you to write to a specified device (standard output is the default device).

                            </div>

                          </div>


                          <p>
                            iex(3)> IO.write(:stdio, “hello world”)<br />
                            hello world<br />
                            :ok

                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>### Writing Files to Memory

One method I did want to highlight is File.open/2.

                            </div>

                          </div>


                          <p>
                            iex(1)> {:ok, file_descriptor} = File.open(“hello world”, [:ram])<br />
                            {:ok, {:file_descriptor, :ram_file, #Port<0.1181>}}<br />
                            iex(17)> :file.read(file_descriptor, 12)
                          </p>


                          <div class="code">
                            <div class="highlight">
                              <pre>Doing it this way lets Elixir operate on the data in memory as if it was a file. You'll notice I call an Erlang :file.read method. This is because I couldn't find anything in Elixir to operate on it.

Summary

There’s quite a bit more to the File, IO, and Path modules in Elixir. This section gave you just a small taste. The next section will be a simple case study application to help you randomly open files.

                            </div>

                          </div>
                          </div3>
                        </div>

                      </div>

                    </div>


                    <div id="cid84" data-tralics-id="cid84" class="chapter" data-number="18">
                      <h1>
                        <a href="#cid84" class="heading hyperref"><span class="number">Chapter 18 </span>Building a Random Image CLI Loader</a>
                      </h1>


                      <p class="noindent">
                        The best way I have found to learn new concepts is to try and build something with what you just learned.<span class="intersentencespace"></span> That’s why I do all the katas.<span class="intersentencespace"></span> So to help ingest our learnings for files, let’s write a CLI (command line interface) application that helps us pick a set of files to randomly open.
                      </p>

                    </div>


                    <div id="cid85" data-tralics-id="cid85" class="section" data-number="18.1">
                      <h2>
                        <a href="#cid85" class="heading hyperref"><span class="number">18.1 </span>Case Study: Building a Random Image CLI Loader with EScript</a>
                      </h2>


                      <p class="noindent">
                        I’ve previously <a href="http://www.binarywebpark.com/first-elixir-cli-application-escript/" target="_blank" rel="noopener">written a tutorial on building an escript CLI application</a>, but we’re going to build another one that does a bit more in this post.
                      </p>


                      <div id="uid216" data-tralics-id="uid216" class="subsection" data-number="18.1.1">
                        <h3>
                          <a href="#uid216" class="heading hyperref"><span class="number">18.1.1 </span>Step 1: Initialize a mix application</a>
                        </h3>


                        <p class="noindent">
                          The first thing to do is to initialize our mix application.<span class="intersentencespace"></span> I’m passing in the *–sup arguments.<span class="intersentencespace"></span> This is to initialize the application with some supervisor and umbrella application defaults.<span class="intersentencespace"></span> It’s more for my own amusement than having anything to do with the application.
                        </p>


                        <p>
                          Below is the mix command I issued and its associated output.
                        </p>


                        <div class="code">
                          <div class="highlight">
                            <pre>$ mix new image_loader --sup
  • creating README.md
  • creating .formatter.exs
  • creating .gitignore
  • creating mix.exs
  • creating config
  • creating config/config.exs
  • creating lib
  • creating lib/image_loader.ex
  • creating lib/image_loader/application.ex
  • creating test
  • creating test/test_helper.exs
  • creating test/imageloadertest.exs

Your Mix project was created successfully. You can use “mix” to compile it, test it, and more:

cd image_loader
mix test

Run “mix help” for more commands.

                          </div>

                        </div>


                        <p>
                          I also did a <em>git init .</em><span class="intersentencespace"></span> command in the image_loader repository so I could use Git version control.
                        </p>

                      </div>

                    </div>


                    <div id="cid86" data-tralics-id="cid86" class="section" data-number="18.2">
                      <h2>
                        <a href="#cid86" class="heading hyperref"><span class="number">18.2 </span>Step 2: Add yaml-elixir and Write Tests</a>
                      </h2>


                      <p class="noindent">
                        Next, I add a yaml parser via <em>yaml-elixir</em> in my <em>mix.exs</em> file.
                      </p>


                      <div class="code">
                        <div class="highlight">
                          <pre># mix.exs

defmodule ImageLoader.MixProject do use Mix.Project

def project do [ app: :imageloader, version: “0.1.0”, elixir: ”~> 1.6”, startpermanent: Mix.env() == :prod, deps: deps() ] end

Run “mix help compile.app” to learn about applications.

def application do [ extraapplications: [:logger, :yamlelixir], mod: {ImageLoader.Application, []} ] end

Run “mix help deps” to learn about dependencies.

defp deps do [ {:yaml_elixir, ”~> 1.3.1”} ] end end

                        </div>

                      </div>


                      <div id="uid217" data-tralics-id="uid217" class="subsubsection" data-number="18.2.1.1">
                        <h4>
                          <a href="#uid217" class="heading">Test Structure</a>
                        </h4>


                        <p class="noindent">
                          Below are the tests I wrote.<span class="intersentencespace"></span> Notice I only test the path generation functionality.<span class="intersentencespace"></span> I could actually check the status of the images when they’re opened, but I chose not to do that.
                        </p>


                        <div class="code">
                          <div class="highlight">
                            <pre># image_loader_test.exs

defmodule ImageLoaderTest do use ExUnit.Case

@file_path “/test/fixtures/test.yml”

test “read yaml from file path into map” do assert ImageLoader.readyamlfromfilepath(@filepath) == %{ “set1” => %{ “base_path” => “/test/fixtures/”, “directory” => “images/”, “files” => [“pexels-photo-87065.jpeg”, “pexels-photo-274054.jpeg”] } } end

test “fetch image paths from yaml file” do assert ImageLoader.imagepaths(@filepath) == %{“set_1” => [”#{File.cwd!}/test/fixtures/images/pexels-photo-87065.jpeg”, ”#{File.cwd!}/test/fixtures/images/pexels-photo-274054.jpeg”]} end end

                          </div>

                        </div>

                      </div>


                      <div id="uid218" data-tralics-id="uid218" class="subsection" data-number="18.2.1">
                        <h3>
                          <a href="#uid218" class="heading hyperref"><span class="number">18.2.1 </span>Step 3: Setup Yaml Structure / File</a>
                        </h3>


                        <p class="noindent">
                          <div class="code">
                            <div class="highlight">
                              <pre># fixtures/test.yml

set1: basepath: “/test/fixtures/” directory: “images/” files: [“pexels-photo-87065.jpeg”, “pexels-photo-274054.jpeg”]

                            </div>

                          </div>
                          </div>


                          <div id="uid219" data-tralics-id="uid219" class="subsection" data-number="18.2.2">
                            <h3>
                              <a href="#uid219" class="heading hyperref"><span class="number">18.2.2 </span>Step 4: Open Images</a>
                            </h3>


                            <p class="noindent">
                              Below is the code used to randomly open up images.<span class="intersentencespace"></span> The main functions are image_paths, which produce the file paths to the images so the System.cmd can know which files to open, and open_images, which does the actual work of opening the images.
                            </p>


                            <p>
                              The function read_yaml_from_file_path parses the yaml file into a map to be parsed through by Elixir.
                            </p>


                            <div class="code">
                              <div class="highlight">
                                <pre># image_loader.ex

defmodule ImageLoader do @moduledoc """ Documentation for ImageLoader. """

Boot up iex and type ImageLoader.open_images(“/test/fixtures/test.yml”)

def openimages(filepath) do imagepaths(filepath) |> Enum.map(fn{set_key, files} -> System.cmd(“open”, files) end) end

def imagepaths(filepath) do readyamlfromfilepath(filepath) |> Enum.reduce(%{}, fn({set, setinfo}, acc) -> Map.merge(acc, %{set => assemblepathsfromset(setinfo)}) end) end

defp assemblepathsfromset(setmap) do basepath = Map.get(setmap, “basepath”, "") dir = Map.get(setmap, “directory”, "") Map.get(setmap, “files”, []) |> Enum.map(fn(file) -> Path.join([File.cwd!, basepath, dir, file]) end) end

def readyamlfromfilepath(filepath) do [File.cwd!, filepath] |> Path.join |> YamlElixir.readfromfile end end

                              </div>

                            </div>

                          </div>


                          <div id="uid220" data-tralics-id="uid220" class="subsection" data-number="18.2.3">
                            <h3>
                              <a href="#uid220" class="heading hyperref"><span class="number">18.2.3 </span>Step 5: Convert to Escript</a>
                            </h3>


                            <p class="noindent">
                              I’ve written about building a CLI with <a href="http://www.binarywebpark.com/first-elixir-cli-application-escript/" target="_blank" rel="noopener">Escript before</a>, but I’ll reiterate the steps here for convenience.
                            </p>


                            <div id="uid221" data-tralics-id="uid221" class="subsubsection" data-number="18.2.3.1">
                              <h4>
                                <a href="#uid221" class="heading">Step 5a: Configure escript in mix.exs</a>
                              </h4>


                              <p class="noindent">
                                The first thing to do is to specify the module with a “main” function that serves as the main module in mix.exs.
                              </p>


                              <div class="code">
                                <div class="highlight">
                                  <pre>defmodule ImageLoader.MixProject do

use Mix.Project

def project do [ app: :imageloader, version: “0.1.0”, elixir: ”~> 1.6”, startpermanent: Mix.env() == :prod, deps: deps(), escript: escript_config() ] end

defp escriptconfig do [mainmodule: ImageLoader.Cli] end

Run “mix help compile.app” to learn about applications.

def application do [ extraapplications: [:logger, :yamlelixir], mod: {ImageLoader.Application, []} ] end

Run “mix help deps” to learn about dependencies.

defp deps do [ {:yaml_elixir, ”~> 1.3.1”} ] end end

                                </div>

                              </div>

                            </div>


                            <div id="uid222" data-tralics-id="uid222" class="subsubsection" data-number="18.2.3.2">
                              <h4>
                                <a href="#uid222" class="heading">Step 5b: Add a module with a main function</a>
                              </h4>


                              <p class="noindent">
                                Next, add the module with the main function that you specified in mix.exs.
                              </p>


                              <div class="code">
                                <div class="highlight">
                                  <pre>defmodule ImageLoader.Cli do

def main(args) do args |> parse_options |> output end

defp parseoptions(args) do {options, \args} = OptionParser.parse!(args, switches: [path: :string] ) options rescue OptionParser.ParseError -> [error: “parse error in your arguments”] end

defp output([error: err] = opts) do IO.puts “Error in opening files: #{err}” end defp output(opts) do ImageLoader.open_images(path(opts)) IO.puts “Images opened from #{path(opts)}” end

defp path(opts), do: opts |> Keyword.get(:path, “/test/fixtures/test.yml”) end

                                </div>

                              </div>

                            </div>


                            <div id="uid223" data-tralics-id="uid223" class="subsubsection" data-number="18.2.3.3">
                              <h4>
                                <a href="#uid223" class="heading">Step 5c: Build the escript</a>
                              </h4>


                              <p class="noindent">
                                Finally, build the escript.
                              </p>


                              <div class="code">
                                <div class="highlight">
                                  <pre>$ mix escript.build
                                </div>

                              </div>

                            </div>

                          </div>


                          <div id="uid224" data-tralics-id="uid224" class="subsection" data-number="18.2.4">
                            <h3>
                              <a href="#uid224" class="heading hyperref"><span class="number">18.2.4 </span>Step 6: Run the CLI program</a>
                            </h3>


                            <p class="noindent">
                              Now, you can run the CLI program.<span class="intersentencespace"></span> Below I run the script using the path to the test.yml file that is included in this program.
                            </p>


                            <div class="code">
                              <div class="highlight">
                                <pre>$ ./image_loader --path="/test/fixtures/test.yml"
                              </div>

                            </div>

                          </div>
                          </div>


                          <div id="cid87" data-tralics-id="cid87" class="section" data-number="18.3">
                            <h2>
                              <a href="#cid87" class="heading hyperref"><span class="number">18.3 </span>Summary</a>
                            </h2>


                            <p class="noindent">
                              Hopefully this CLI tool has given you a feel for what you can do with some of Elixir’s file related modules.<span class="intersentencespace"></span> Coming up soon, we’ll talk about errors in Elixir.
                            </p>

                          </div>


                          <div id="cid88" data-tralics-id="cid88" class="chapter" data-number="19">
                            <h1>
                              <a href="#cid88" class="heading hyperref"><span class="number">Chapter 19 </span>Everyone Makes Mistakes: Errors in Elixir</a>
                            </h1>


                            <p class="noindent">
                              I once took a class in watercolor painting.<span class="intersentencespace"></span> The instructor would have us sketch a bit, and then we’d start adding our paint.<span class="intersentencespace"></span> You had to be very careful not only with the amount of water you used, but also to let certain areas dry before you attempted to paint.<span class="intersentencespace"></span> Otherwise the colors would run together and there was no going back.<span class="intersentencespace"></span> There was no such thing as being able to “rescue” errors in watercolor painting.
                            </p>


                            <p>
                              Fortunately, Elixir does provide error handling.
                            </p>

                          </div>


                          <div id="cid89" data-tralics-id="cid89" class="section" data-number="19.1">
                            <h2>
                              <a href="#cid89" class="heading hyperref"><span class="number">19.1 </span>Elixir Philosophy: Let It Crash</a>
                            </h2>


                            <p class="noindent">
                              If you hang around the Elixir community long enough, you’ll hear phrases like “let it crash.”<span class="intersentencespace"></span> This refers to the fact that Elixir can do things like let an exit message from a dying process be used by a supervisor to decide what to do.
                            </p>

                          </div>


                          <div id="cid90" data-tralics-id="cid90" class="section" data-number="19.2">
                            <h2>
                              <a href="#cid90" class="heading hyperref"><span class="number">19.2 </span>Conventions</a>
                            </h2>


                            <p class="noindent">
                              In Elixir, the convention is to create a non-bang function such as hello_world/1 that returns a tuple consisting of a status and a result (e.g., {:ok, result} or {:error, reason}).
                            </p>


                            <p>
                              You also create a bang function that returns the result or raises an exception.<span class="intersentencespace"></span> For example., hello_world!/1 could return “result” or raise a HelloException.
                            </p>

                          </div>


                          <div id="cid91" data-tralics-id="cid91" class="section" data-number="19.3">
                            <h2>
                              <a href="#cid91" class="heading hyperref"><span class="number">19.3 </span>Error Handling Keywords</a>
                            </h2>


                            <p class="noindent">
                              Before diving in to error handling, let’s go over some of the basic keywords you’ll encounter.
                            </p>


                            <div id="uid225" data-tralics-id="uid225" class="subsection" data-number="19.3.1">
                              <h3>
                                <a href="#uid225" class="heading hyperref"><span class="number">19.3.1 </span>try</a>
                              </h3>


                              <p class="noindent">
                                The try keyword tells Elixir to enter into the block and “try” something that may result in an error.
                              </p>

                            </div>


                            <div id="uid226" data-tralics-id="uid226" class="subsection" data-number="19.3.2">
                              <h3>
                                <a href="#uid226" class="heading hyperref"><span class="number">19.3.2 </span>catch</a>
                              </h3>


                              <p class="noindent">
                                The catch keyword can be used with try, although as the Elixir documentation points out, it is very uncommon to use it this way.<span class="intersentencespace"></span> Instead, you’ll use it with the throw keyword.
                              </p>

                            </div>


                            <div id="uid227" data-tralics-id="uid227" class="subsection" data-number="19.3.3">
                              <h3>
                                <a href="#uid227" class="heading hyperref"><span class="number">19.3.3 </span>throw</a>
                              </h3>


                              <p class="noindent">
                                Throw is used in conjunction with catch in situations where it is not possible to get a value without using throw/catch.
                              </p>

                            </div>


                            <div id="uid228" data-tralics-id="uid228" class="subsection" data-number="19.3.4">
                              <h3>
                                <a href="#uid228" class="heading hyperref"><span class="number">19.3.4 </span>rescue</a>
                              </h3>


                              <p class="noindent">
                                Rescue allows you to specify what happens when a certain exception is raised.
                              </p>

                            </div>


                            <div id="uid229" data-tralics-id="uid229" class="subsection" data-number="19.3.5">
                              <h3>
                                <a href="#uid229" class="heading hyperref"><span class="number">19.3.5 </span>raise</a>
                              </h3>


                              <p class="noindent">
                                Raise is the keyword that allows you to raise an error in Elixir.
                              </p>

                            </div>


                            <div id="uid230" data-tralics-id="uid230" class="subsection" data-number="19.3.6">
                              <h3>
                                <a href="#uid230" class="heading hyperref"><span class="number">19.3.6 </span>after</a>
                              </h3>


                              <p class="noindent">
                                The after keyword specifies something that must always happen.
                              </p>

                            </div>

                          </div>


                          <div id="cid92" data-tralics-id="cid92" class="section" data-number="19.4">
                            <h2>
                              <a href="#cid92" class="heading hyperref"><span class="number">19.4 </span>Examples of Try/Rescue</a>
                            </h2>


                            <p class="noindent">
                              Let’s look at using try and rescue in practice.
                            </p>


                            <div id="uid231" data-tralics-id="uid231" class="subsection" data-number="19.4.1">
                              <h3>
                                <a href="#uid231" class="heading hyperref"><span class="number">19.4.1 </span>Example From the Phoenix Framework</a>
                              </h3>


                              <p class="noindent">
                                Let’s say we had a method to fetch a “Car” model in Phoenix.<span class="intersentencespace"></span> With a bang get!/1 method, an Ecto.NoResultsError is raised.
                              </p>


                              <div class="code">
                                <div class="highlight">
                                  <pre>def get_my_car do

try do car = Repo.get!(Car, 4) rescue Ecto.NoResultsError -> {:error, “not_found”} end end

                                </div>

                              </div>


                              <p>
                                You could also omit the “try” block and simply use rescue.
                              </p>


                              <div class="code">
                                <div class="highlight">
                                  <pre>def get_my_car do

car = Repo.get!(Car, 4) rescue Ecto.NoResultsError -> {:error, “not_found”} end

                                </div>

                              </div>


                              <p>
                                This example fits the canonical use case of using raise/rescue for exception handling.<span class="intersentencespace"></span> This is for unexpected situations your program gets into.
                              </p>

                            </div>

                          </div>


                          <div id="cid93" data-tralics-id="cid93" class="section" data-number="19.5">
                            <h2>
                              <a href="#cid93" class="heading hyperref"><span class="number">19.5 </span>Examples of Throw/Catch</a>
                            </h2>


                            <p class="noindent">
                              When you have expected failures, it’s time for throw/catch.<span class="intersentencespace"></span> I’ll summarize the findings from this StackOverflow answer<sup id="cha-19_footnote-ref-1" class="footnote"><a href="#cha-19_footnote-1">1</a></sup> on throws which gives some more interesting insights and you can read if you’d like.
                            </p>


                            <p>
                              The Elixir documentation<sup id="cha-19_footnote-ref-2" class="footnote"><a href="#cha-19_footnote-2">2</a></sup> says that throw/catch is good to use when interfacing with library code that does not provide a “proper API”.
                            </p>


                            <p>
                              As an example, let’s say Elixir didn’t provide a way to delete an element(s) from a list.
                            </p>


                            <p>
                              Then you might use throw this way:
                            </p>


                            <div class="code">
                              <div class="highlight">
                                <pre>try do

m = [:t, :u, :v] Enum.each m, fn(y) -> if y == :u, do: throw([:t, :v]) end “Nothing to catch” catch list -> list end

                              </div>

                            </div>


                            <p>
                              One cool example comes from <a href="https://github.com/elixir-ecto/ecto/blob/428126157b1970d10f9d5233397f07c35ce69cac/test/support/test_repo.exs#L84-L98" target="_blank" rel="noopener">Ecto</a>:
                            </p>


                            <div class="code">
                              <div class="highlight">
                                <pre>def transaction(_repo, _opts, fun) do

Makes transactions “trackable” in tests

send self, {:transaction, fun} try do {:ok, fun.()} catch :throw, {:ecto_rollback, value} -> {:error, value} end end

def rollback(_repo, value) do send self, {:rollback, value} throw {:ecto_rollback, value} end

                              </div>

                            </div>


                            <p>
                              Above we can see that we’ll catch a rollback when we try a transaction in Ecto.
                            </p>


                            <p>
                              The StackOverflow post I referenced<sup id="cha-19_footnote-ref-3" class="footnote"><a href="#cha-19_footnote-3">3</a></sup> goes on to say that using raise/rescue is good when you want to have a programmer looking at a stacktrace.<span class="intersentencespace"></span> You can use throw/catch when you don’t want to incur the cost of building that stacktrace.
                            </p>

                          </div>


                          <div id="cid94" data-tralics-id="cid94" class="section" data-number="19.6">
                            <h2>
                              <a href="#cid94" class="heading hyperref"><span class="number">19.6 </span>Examples of Try/After</a>
                            </h2>


                            <p class="noindent">
                              We use try/after when we want to ensure an action occurs no matter what.<span class="intersentencespace"></span> As an example, we may want to make sure a file gets closed or a status message gets logged.
                            </p>


                            <div class="code">
                              <div class="highlight">
                                <pre>try do

IO.inspect “Executing some code…” rescue err in RuntimeError -> IO.puts “Error #{err}” after Logger.info fn -> “We have at least tried to execute some code.” end

                              </div>

                            </div>

                          </div>


                          <div id="cid95" data-tralics-id="cid95" class="section" data-number="19.7">
                            <h2>
                              <a href="#cid95" class="heading hyperref"><span class="number">19.7 </span>Scope in Try/Rescue/Catch/After</a>
                            </h2>


                            <p class="noindent">
                              Regarding variable scope, one thing to note is that variables defined in the try/rescue/catch/after context are not available in the “outer context”.<span class="intersentencespace"></span> This is in keeping with traditional Elixir semantics.
                            </p>


                            <p>
                              So if you’re trying to capture a value that is set in a try/catch/rescue/after block, you’ll want to do something like this:
                            </p>


                            <div class="code">
                              <div class="highlight">
                                <pre>status =

try do raise “failure” :failure*status rescue

  • -> :wearerescued end

status is now set to :wearerescued

                              </div>

                            </div>

                          </div>


                          <div id="cid96" data-tralics-id="cid96" class="section" data-number="19.8">
                            <h2>
                              <a href="#cid96" class="heading hyperref"><span class="number">19.8 </span>Summary</a>
                            </h2>


                            <p class="noindent">
                              Unlike watercolor painting, Elixir provides us with a way to handle our errors.<span class="intersentencespace"></span> Just like watercolor errors do happen, but we can ensure we have some mechanisms to deal with them when they occur.
                            </p>


                            <div id="uid235" data-tralics-id="uid235" class="subsection" data-number="19.8.1">
                              <h3>
                                <a href="#uid235" class="heading hyperref"><span class="number">19.8.1 </span>Footnotes</a>
                              </h3>

                            </div>

                          </div>


                          <div id="cha-19_footnotes">
                            <ol class="footnotes">
                              <li id="cha-19_footnote-1">
                                <a href="https://stackoverflow.com/questions/40280887/elixir-try-catch-vs-try-rescue" target="_blank" rel="noopener">Source: Elixir - try/catch vs try/rescue?</a> <a class="arrow" href="#cha-19_footnote-ref-1">↑</a>
                              </li>


                              <li id="cha-19_footnote-2">
                                <a href="https://elixir-lang.org/getting-started/try-catch-and-rescue.html#throws" target="_blank" rel="noopener">Source: Throws section</a> <a class="arrow" href="#cha-19_footnote-ref-2">↑</a>
                              </li>


                              <li id="cha-19_footnote-3">
                                <a href="https://stackoverflow.com/questions/40280887/elixir-try-catch-vs-try-rescue" target="_blank" rel="noopener">Source: Elixir - try/catch vs try/rescue?</a> <a class="arrow" href="#cha-19_footnote-ref-3">↑</a>
                              </li>

                            </ol>

                          </div></div>