Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

October 17th

livebooks/October_17.livemd

October 17th

Section

defmodule Math do
  def identity(x) do
    x
  end

  def largest(num1, num2) do
    if num1 > num2 do
      num1
    else
      num2
    end
  end

  def smallest(num1, num2) when num1 < num2, do: num1
  def smallest(_, num2), do: num2
end
Math.smallest(3000, 3000)
Math.identity(37)
Math.largest(5000, 5000)
defmodule BMI do
  def bmi(height, weight) do
    weight / (height * height)
  end
end
BMI.bmi(1.55, 55)

Data Structures

  • List
  • Tuple

Lists

[1, 3, 5]
  • Integers
  • Floating point numbers
  • Strings
  • Atoms
  • Booleans
[1, 20.3, "third", :atomic, true]
[69, "string", [1, 20.3, "third", :atomic, true], [1, [9]]]

Tuples

{1, 3, 5}

Pattern Matching (=)

x = 5
height = 155
{height, weight} = {159, 56}
height
weight
defmodule Person do
  def get_name({:name, name}), do: name
  def get_name({:nome, name}), do: name
  def get_name({:nombre, name}), do: name
end
Person.get_name({:name, 12})
Person.get_name({:nome, "Adolfo"})
Person.get_name({:nombre, "Martha"})
defmodule BMI2 do
  def compute(height, weight) when is_number(height) and is_number(weight) do
    weight / (height * height)
  end

  def compute({height, :meters}, {weight, :kilograms}) do
    weight / (height * height)
  end

  def compute({height, :centimeters}, {weight, :kilograms}) do
    compute({height / 100, :meters}, {weight, :kilograms})
  end
end
BMI2.compute({1.75, :meters}, {75, :kilograms})
BMI2.compute({175, :centimeters}, {75, :kilograms})
BMI2.compute(1.75, 75)
{:name, name, _, _} = {:name, "Martha", :weight, 55}

Pattern Matching in Lists

a_list = [1, 3, 5]
head = hd(a_list)
tail = tl(a_list)
head
tail
[head | tail]
[head2 | tail2] = [42, :idontknow, "Tijuana", 156.25658]
head2
tail2
[_ | tail3] = [1, 452, :atom]
tail3
[_, _, 3, game | tail] = [4548.55, 56599, 3, "tic-tac-toe", "jogo da velha", "Dia de Muertos"]
game
tail
defmodule Find do
  def largest(a_list) when is_list(a_list), do: largest(a_list, 0)

  def largest(_), do: "Wrong argument, please add a list"

  defp largest([], largest_so_far), do: largest_so_far

  defp largest([head | tail], largest_so_far) do
    if head > largest_so_far do
      largest(tail, head)
    else
      largest(tail, largest_so_far)
    end
  end
end
Find.largest([1, 222, 32])
Find.largest(45)
Find.largest([])

New version of Find

defmodule Find2 do
  def largest([head | tail] = a_list) when is_list(a_list), do: largest(tail, head)

  def largest(_), do: {:error, "Wrong argument, please add a list"}

  defp largest([], largest_so_far), do: largest_so_far

  defp largest([head | tail], largest_so_far) do
    if head > largest_so_far do
      largest(tail, head)
    else
      largest(tail, largest_so_far)
    end
  end
end
Find2.largest([-12, -888, -127, -54])
Find2.largest([])