Powered by AppSignal & Oban Pro

Advanced Pattern Matching and Constructors

3. advanced_pattern_matching_and_constructors.livemd

Advanced Pattern Matching and Constructors

Comparison Across Tuples

defmodule Comparison do
  def origin?({0, 0}), do: true
  def origin?(_point), do: false

  # guard -> when x == y
  # def identity?({x,y}) when x == y, do: true  
  def identity?({i, i}), do: true
  def identity?(_point), do: false
end
{:module, Comparison, <<70, 79, 82, 49, 0, 0, 6, ...>>, {:identity?, 1}}
import Comparison

IO.inspect(Comparison.origin?({0, 0}))
IO.inspect(Comparison.identity?(5))
IO.inspect(Comparison.identity?({5, 5}))
true
false
true
true

Constructors

defmodule Point do
  def origin, do: {0, 0}
  def right({x, y}), do: {x + 1, y}
  def left({x, y}), do: {x - 1, y}
  def up({x, y}), do: {x, y - 1}
  def down({x, y}), do: {x, y + 1}
  def mirror({x, y}, w), do: {w - x, y}
  def flip({x, y}, h), do: {x, h - y}
  def transpose({x, y}), do: {y, x}
  def move({x, y}, {cx, cy}), do: {x + cx, y + cy}

  def rotate(point, 0, _w, _h) do
    point
  end

  def rotate(point, 90, w, _h) do
    point
    |> transpose
    |> mirror(w)
  end

  def rotate(point, 180, w, h) do
    point
    |> flip(h)
    |> mirror(w)
  end

  def rotate(point, 270, _w, h) do
    point
    |> flip(h)
    |> transpose
  end

  def new(x, y) when is_integer(x) and is_integer(y) do
    {x, y}
  end
end
{:module, Point, <<70, 79, 82, 49, 0, 0, 13, ...>>, {:new, 2}}
import Point

Point.origin()
|> Point.right()
|> Point.right()

Point.new(1, 2)

Point.new(1, :two)