Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.