Elixir Pattern Matching

From Elixir Wiki
Jump to navigation Jump to search

Elixir Pattern Matching[edit]

Introduction[edit]

Pattern matching is a fundamental concept in the Elixir programming language. It allows developers to match data structures against patterns to perform specific actions based on the matched pattern. Pattern matching is heavily used in Elixir to destructure data, perform conditional branching, and normalize code. This article explains the key concepts and syntax of pattern matching in Elixir.

Syntax[edit]

In Elixir, pattern matching is performed using the `=` operator. The left-hand side of the `=` operator is the pattern, and the right-hand side is the value to match against. Here are some examples:

Matching Variables[edit]

``` x = 42 ```

Matching Values[edit]

``` 42 = x ```

Matching Tuples[edit]

``` {1, 2, 3} = {a, b, c} ```

Matching Lists[edit]

``` [head | tail] = [1, 2, 3, 4, 5] ```

Matching Maps[edit]

``` %{name: "John", age: age} = %{name: "John", age: 30} ```

Pattern Matching and Functions[edit]

Pattern matching plays a vital role in Elixir functions. When defining functions, multiple function clauses can be used, each having a different pattern to match against. Elixir will automatically select the appropriate function clause based on the matched pattern.

Advanced Pattern Matching[edit]

Elixir supports various advanced techniques for pattern matching, making it a powerful tool in functional programming. Some of these techniques include:

Guards[edit]

``` defmodule Math do

 def factorial(n) when n < 0, do: "Invalid input"
 def factorial(0), do: 1
 def factorial(n), do: n * factorial(n-1)

end ```

Pin Operator[edit]

``` {a, ^a} = {1, 1} ```

Ignoring Values[edit]

``` {:ok, _} = {:ok, "Some value"} ```

Pattern Matching in Function Heads[edit]

``` defmodule MyList do

 def sum([head | tail]), do: head + sum(tail)
 def sum([]), do: 0

end ```

Conclusion[edit]

Pattern matching is a powerful feature in Elixir that allows developers to manipulate and destructure data in a concise and expressive way. It is an essential tool for writing clear and maintainable code in Elixir.

See Also[edit]