Last active
April 29, 2020 18:53
-
-
Save seanhandley/3292ddbb2c1c36500ac4b94eee0c9caf to your computer and use it in GitHub Desktop.
Elixir Pattern Matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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