A Mad Dash Through Elixir Types


Elixir for Programmers, Second Edition

Notes

  1. ?≠ returns a codepoint: 8800.

  2. Dividing two integers returns a float. Use div and trunc to get integer results.

  3. In Elixir, nil is false.

  4. Regular expressions are based on PCRE (Perl lives on!).

  5. =~ performs a regular expression match

    iex> str = "once upon a time"
    iex> str =~ ~r/u..n/
    true

  6. =~ also accepts a string as its right hand argument, in which case it returns true if the left string contains the right.

  7. Lists are not arrays. You cannot calculate an offset to a specific element.

  8. map[:missingKey] returns nil. map.missingKey raises an exception.

Exercises

Strings

  • Interpolate current date/time using double-quoted string and a sigil.

    iex> now = Time.utc_now
    
    iex> "The time is approximately #{now.hour}:#{now.minute} UTC."
    "The time is approximately 13:34 UTC."
    
    iex> ~s/The time is approximately #{now.hour}:#{now.minute} UTC./
    "The time is approximately 13:34 UTC."

  • Use IO.puts to output: 1 + 2 = #{ 1 + 2 }

    iex> IO.puts(~S"1 + 2 = #{ 1 + 2 }")
    1 + 2 = #{ 1 + 2 }
    :ok

  • Convert string into a list of words.

    iex> ~w/now is the time/
    ["now", "is", "the", "time"]

Regular Expressions

  • Return true if string contains an a, followed by any single character, followed by a c.

    iex> str =~ ~r/a.c/
    true

  • Replace every occurrence of cat with dog`.

    iex>  Regex.replace(~r/cat/, "double cat cats", "dog")
    "double dog dogs"

  • Replace only the first occurrence:

    iex>  Regex.replace(~r/cat/, "double cat cats", "dog", global: false)
    "double dog cats"

All notes and comments are my own opinion. Follow me at @rgacote@genserver.social