Tuple and List
Basic Tuple
person = {"Aldi", 25, :male}
IO.inspect(person)
new_person = person # deep copy
IO.puts("Name: #{elem(new_person, 0)}")
updated_person = put_elem(new_person, 1, 26)
IO.inspect(updated_person)
# check the person again
IO.inspect(person)
Tuple
people = ["aldi", "wildan", "aya", "azzara"]
IO.puts(people) # concatenated
IO.inspect(people) # printed with actual data type (list, tuple, etc)
IO.puts(hd(people)) # head
IO.puts(List.last(people)) # tail
people = ["muhammad" | people]
IO.inspect(people)
IO.puts(hd(people))
people = ["ayaazzara" | people]
IO.inspect(people)
people = tl(people)
IO.inspect(people)
# concat
people = people ++ ["ayaazzara"]
IO.inspect(people)
IO.inspect(List.last(people))
# remove with --
# elixir compare each string, if name are doubled, then it will removed one by one
# this case, only remove aldi once
people = ["aldi" | people] -- ["aya", "aldi"]
IO.inspect(people)
With Pattern Matching
{status, message} = {:ok, "Success"}
IO.puts(status)
IO.puts(message)
{a, b} = {:error}
# expected to be error
# tuple matching
defmodule Response do
def handle_response({:ok, msg}), do: "Success: #{msg}"
def handle_response({:error, msg}), do: "Error: #{msg}"
end
IO.puts(Response.handle_response({:ok, "All good"}))
# "Success: All good"
IO.puts(Response.handle_response({:error, "Something went wrong"}))
# "Error: Something went wrong"
[head | tail] = [1,2,3,4,5]
IO.puts(head)
IO.inspect(tail)
[1, 2, x] = [1, 2] # error bolo, the length must be the same
[1, 2, x] = [1, 2, "aldi"]
IO.puts(x) # aldi
defmodule ListMatcher do
def process([first, second | _]), do: "First #{first}, Second #{second}"
def process([]), do: "Empty!"
def process(), do: nil # returned, without visual output hahaha
end
IO.puts(ListMatcher.process([10, 30, 50]))
IO.puts(ListMatcher.process([]))
IO.puts(ListMatcher.process())
{status, [first | _]} = {:ok, [1, 3, 5]}
IO.puts(status)
IO.puts(first)