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
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")
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)
names = ["Louise", "Tom", "Fred"]
Uses
names ++ ["Judy", "Mac"]
names -- ["Louise"]
List.first(list)
List.last(name)
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)
:age
:name
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
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
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
Integer.to_string(12345) |> String.to_integer |> Math.sum(20)
String.upcase("hello") |> String.split("") |> length
^ Also known as functional composition
Enum.each(names, fn(name) -> IO.puts name end)
Enum.each(names, &(IO.puts(&1)))
Enum.map(names, fn(name) -> String.upcase(name) end)