Skip to content

Instantly share code, notes, and snippets.

@claritee
Last active October 16, 2018 01:41
Show Gist options
  • Save claritee/7ec687e441427435100b78df61bb4334 to your computer and use it in GitHub Desktop.
Save claritee/7ec687e441427435100b78df61bb4334 to your computer and use it in GitHub Desktop.
Introduction to Elixir

Elixir Runthrough

This is a list of commands that will be used at a Women Who Code Workshop on Elixir in Sydney, during an introduction to Elixir

IEX

iex

Strings

name = "John Doe"
IO.puts name

Uses

IO.puts "Hi #{name}"
String.length(name)
String.upcase(name)
String.downcase(name)
String.starts_with?(name, "J")
String.reverse("hello")

Numerics

age = 30
height = 170.5

Uses

is_integer(age)
is_float(height)
is_integer(height)
IO.puts "John is #{age} and is #{height} cms tall."

age + 10
age * 2
age/2

div(9, 4)
rem(9,4)

Integer

require Integer
Integer.is_even(2)
Integer.is_odd(2)

Lists

names = ["Louise", "Tom", "Fred"]

Uses

names ++ ["Judy", "Mac"]
names -- ["Louise"]
List.first(list)
List.last(name)

Maps

person = %{name: "Judy", age: 30, city: "Sydney"}

Uses

person.name
person[:name]

Map.get(person, :name)
Map.get(person, :x)

Map.fetch(person, :name)
Map.fetch(person, :x)
Map.fetch!(person, :x)

job_details = %{occupation: "Scientist", industry: "Medical Science"}
Map.merge(person, job_details)

Atoms

:age
:name

Pattern Matching

x = 1
^x = 2
x = 2

{x, y} = {10, 20}

%{name: name, age: age} = %{name: "Penny", age: 42}
name
age

[head | tail] = names
head
tail

Conditionals

if-else

if 2 == 2 do
  IO.puts "2 == 2 is true"
end

if 2 == 2, do: IO.puts "2 == 2 is true"

if 2 == 3 do
  IO.puts "that was true"
else
  IO.puts "2 == 3 is not true"
end

unless

unless 2 == 3 do
  IO.puts "that was true"
end

case (test value)

num = 20
case num do
  1 -> IO.puts "equals 1"
  11 -> IO.puts "equals 11"
  20 -> IO.puts "equals 20"
  _ -> false
end

cond (test code evaluation)

cond do
  num + 1 == 30 -> "Result is 30"
  num + 1 == 40 -> "Result is 40"
  num + 1 == 21 -> "Result is 21"
end

Modules and Functions

Function

sum = fn (a, b) -> a + b end
sum.(1,2)

Modules

defmodule Math do
  def sum(a, b) do
    a + b
  end
end

Math.sum(1, 2)

Public and private functions

def
defp

Pipe Operator

Integer.to_string(12345) |> String.to_integer |> Math.sum(20)
String.upcase("hello") |> String.split("") |> length

^ Also known as functional composition

Enum

Enum.each(names, fn(name) -> IO.puts name end)
Enum.each(names, &(IO.puts(&1)))

Enum.map(names, fn(name) -> String.upcase(name) end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment