Learn By Example: Elixir Pattern matching

Here’s an easy to follow code example on Elixir pattern matching

Pattern matching is a rare language feature that Elixir includes. It’s quite similar to de-structuring that you’d find in other languages, but with some other nuances. I’ll focus on its similarities to de-structuring for now.

				
					defmodule Response do
  defstruct body: ""
end

defmodule ErrorResponse do
  defstruct body: "", status: 0
end

defmodule Api do
  def call(endpoint) when endpoint == "a" do
    {%Response{body: "<html><body>Hello</body></html>"}, nil}
  end

  def call(endpoint) when endpoint == "b" do
    {nil, %ErrorResponse{body: ~s({errors: [{message: "An error occured", status: 503}]}), status: 503}}
  end
end

defmodule Main do
  def main do
    {:ok, integer} = {:ok, 13} # makes an assertion that the second item in the tuple exists and assigns that value to integer, otherwise throws an error

    IO.inspect(integer)

    # 13

    {response, err} = Api.call("a") # this might not be idiomatic, but gets the point across

    if response do
      IO.inspect(response, label: "response from a")
      # response from a: %Response{body: "<html><body>Hello</body></html>"}
    end

    if err do
      IO.inspect(err, label: "err from a")
    end

    {response, err} = Api.call("b")

    if response do
      IO.inspect(response, label: "response from b")
    end

    if err do
      IO.inspect(err, label: "err from b")
      # err from b: %ErrorResponse{
  body: "{errors: [{message: \"An error occured\", status: 503}]}",
  status: 503
}
    end
  end
end

Main.main()

				
			

Never miss another post!

Get my latest articles delivered directly to your inbox.

Never miss another post!

Get my latest articles delivered directly to your inbox.

Upcoming Course

Break Free From Tutorials!

A software development course that doesn’t get you stuck with specifics from a tutorial, but challenges you to think like a software architect. 

🙏

Great Choice!

Thanks for enabling notifications! Don’t worry, I hate spam too and I won’t ever disclose your contact information to 3rd parties.