Skip to content

Instantly share code, notes, and snippets.

View BrooklinJazz's full-sized avatar

Brooklin Myers BrooklinJazz

View GitHub Profile
[1, 2] ++ [3, 4] # [1, 2, 3, 4]
[1, 2, 3] -- [1, 3] # [2]
[1, 2, 3] -- [1] # [2, 3]
[1, 2, 3] -- [3, 1] # [2]
@BrooklinJazz
BrooklinJazz / enum.ex
Created June 7, 2021 18:37
Elixir Enum Examples
Enum.map([1, 2, 3], fn x -> x * 2 end) # [2, 4, 6]
Enum.sum([1, 2, 3]) # 6
Enum.map(1..3, fn x -> x * 2 end) # [2, 4, 6]
Enum.sum(1..3) # 6
map = %{"a" => 1, "b" => 2}
Enum.map(map, fn {k, v} -> {k, v * 2} end) # [{"a", 2}, {"b", 4}]
@BrooklinJazz
BrooklinJazz / datatypes.ex
Last active July 3, 2022 22:31
Example Data Types for Elixir
1 # integer
0b1010 # 10 integer in binary
0o777 # 511 integer in octal
0x1F # 31 integer in hexadecimal
1.2 # float
:example # atom
"hello" # string
true # boolean
false # boolean
[1, 2, 3] # list
@BrooklinJazz
BrooklinJazz / example.ex
Created June 7, 2021 18:08
Calling a function from inside the same module
defmodule Greeting do
def main do
say_hello()
end
def say_hello do
"Hello"
end
end
Greeting.main() # Hello
@BrooklinJazz
BrooklinJazz / example.ex
Created June 7, 2021 18:04
Demonstrate elixir functions with different parameters
defmodule Greeting do
def say_hello do
"Hello"
end
def say_hello(name) do
"Hello #{name}"
end
def say_hello(name1, name2) do
"Hello #{name1}, Hi #{name2}"
end
@BrooklinJazz
BrooklinJazz / ternary.ex
Created June 7, 2021 17:48
ternary example
if(true, do: "code to run when true", else: "code to run when false")
# brackets are optional
if true, do: "code to run when true", else: "code to run when false"
@BrooklinJazz
BrooklinJazz / if.ex
Created June 7, 2021 17:43
if example
if true do
# code to run when true
else
# code to run when false
end
@BrooklinJazz
BrooklinJazz / unless.ex
Created June 7, 2021 17:43
unless example
unless false do
# code to run when false
else
# code to run when true
end
@BrooklinJazz
BrooklinJazz / case.ex
Created June 7, 2021 17:41
case example
case 1 do
1 -> "the 1 path is executed"
2 -> "the 2 path is skipped"
_ -> "the default path is skipped"
end
case 2 do
1 -> "the 1 path is skipped"
2 -> "the 2 path is executed"
_ -> "the default path is skipped"
@BrooklinJazz
BrooklinJazz / cond.ex
Last active June 7, 2021 17:37
cond example
cond do
5 < 3 -> "this will be skipped"
4 == 4 and 5 > 3 -> "this code will execute"
end