Skip to content

Instantly share code, notes, and snippets.

@seanhandley
Last active April 29, 2020 18:53
Show Gist options
  • Save seanhandley/3292ddbb2c1c36500ac4b94eee0c9caf to your computer and use it in GitHub Desktop.
Save seanhandley/3292ddbb2c1c36500ac4b94eee0c9caf to your computer and use it in GitHub Desktop.
Elixir Pattern Matching
defmodule Plane do
defstruct is_fueled?: false, has_pilot?: false
def take_off(plane) do
case plane do
%Plane{ is_fueled?: false } ->
:needs_fuel
%Plane{ has_pilot?: false } ->
:needs_pilot
_ ->
:whoosh!
end
end
end
plane = %Plane{is_fueled?: true}
Plane.take_off(plane)
# => :needs_pilot
plane = %Plane{has_pilot?: true}
Plane.take_off(plane)
# => :needs_fuel
plane = %Plane{has_pilot?: true, is_fueled?: true}
Plane.take_off(plane)
# => :whoosh!
defmodule Plane do
defstruct is_fueled?: false, has_pilot?: false
def take_off(%Plane{ is_fueled?: false }), do: :needs_fuel
def take_off(%Plane{ has_pilot?: false }), do: :needs_pilot
def take_off(%Plane{}), do: :whoosh!
end
plane = %Plane{is_fueled?: true}
Plane.take_off(plane)
# => :needs_pilot
plane = %Plane{has_pilot?: true}
Plane.take_off(plane)
# => :needs_fuel
plane = %Plane{has_pilot?: true, is_fueled?: true}
Plane.take_off(plane)
# => :whoosh!
defmodule Plane do
defstruct is_fueled?: false, has_pilot?: false
def take_off(plane) do
with %Plane{is_fueled?: true} <- plane,
%Plane{has_pilot?: true} <- plane do
:whoosh!
else
%Plane{is_fueled?: false} -> :needs_fuel
%Plane{has_pilot?: false} -> :needs_pilot
end
end
end
plane = %Plane{is_fueled?: true}
Plane.take_off(plane)
# => :needs_pilot
plane = %Plane{has_pilot?: true}
Plane.take_off(plane)
# => :needs_fuel
plane = %Plane{has_pilot?: true, is_fueled?: true}
Plane.take_off(plane)
# => :whoosh!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment