November 23, 2020 · Elixir Learn By Example ·

Learn By Example: Elixir Pattern matching

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket

Pattern matching is something that's a rare language feature that Elixir includes. It's quite similar to destructuring that you'd find in other languages, but with some other nuances. I'll focus on its similarities to destructuring 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()

Subscribe by Email

Get my latest content straight to your email

    We won't send you spam. Unsubscribe at any time.
    Powered By ConvertKit
    If you have any questions about this article