Skip to content

Instantly share code, notes, and snippets.

@smashedlife
Last active August 29, 2015 14:21
Show Gist options
  • Save smashedlife/adb9e138e0649d53ae40 to your computer and use it in GitHub Desktop.
Save smashedlife/adb9e138e0649d53ae40 to your computer and use it in GitHub Desktop.

Programming Elixir Exercises

Chapter 2 - Pattern Matching

Exercise: Pattern Matching 2

Which of the following will match

[ a, b, a ] = [ 1, 2, 3 ]
# (MatchError) no match of right hand side value: [ 1, 2, 3 ]

[ a, b, a ] = [ 1, 1, 2 ]
# (MatchError) no match of right hand side value: [ 1, 1, 2 ]

[ a, b, a ] = [ 1, 2, 3 ]
# [ 1, 2, 1 ]

Exercise: Pattern Matching 3

If you assume the variable a initially contains the value 2, which of the following will match?

[ a, b, a ] = [ 1, 2, 3 ]
# (MatchError) No match of right hand side value: [ 1, 2, 3 ]

[ a, b, a ] = [ 1, 1, 2 ]
# (MatchError) No match of right hand side value: [ 1, 1, 2 ]

a = 1
# 1

^a = 2
# (MatchError) No match of right hand side value: 2

^a = 1
# 1

^a = 2 - a
# 1

Chapter 3 - Immutability

NOTES

  • All values are immutable.
  • Once a variable references a value, it will always reference those same values until you rebind the variable
  • If you need to add an element to say, an array, Elixir will make a copy of original containing the new value. The original will remain unchanged.
  • Since Elixir knows that existing data is immutable, it can reuse it, in part or as a whole, when building new structures
    list1 = [ 3, 2, 1 ]
    # [ 3, 2, 1 ]
    
    list2 = [ 4 | list1 ]
    # [ 4, 3, 2, 1]

  • Elixir allows you to write your code using lots of processes and each process has its own heap. Since each process is much smaller, garbage collection is much faster. If a process terminates before its heap becomes full, all its data is discaded. No garbage collection is required in this instance.
  • Any function that transform data will return a new copy of it. It will never modify it in place.
    name = "elixir"
    "elixir"
    
    cap_name = String.capitalize name
    "Elixir"
    
    name
    "elixir"

Chapter 4 - Elixir Basics

NOTES

Built-in Types:

  • Value types:
    • Arbitrary-sized integers
    • Floating-point numbers
    • Atoms
    • Ranges
    • Regular expressions
  • System types:
    • PIDs and ports
    • References
  • Collection types:
    • Tuples
    • Lists
    • Maps
    • Binaries

Integers

  • Integer literals can be written as decimals (1234), hexadecimals (0xcafe), octal (0o785) and binary (0b1010)
  • Floa
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment