Pattern matching

From Elixir Wiki
Jump to navigation Jump to search

Pattern Matching[edit]

File:Pattern matching.png
Example of pattern matching in Elixir

Pattern matching is a fundamental feature of the Elixir programming language. It allows developers to match against data structures and bind variables to different parts of the matched structure, enabling powerful operations and transformations.

Syntax[edit]

Pattern matching in Elixir uses the `=` operator to match the left-hand side pattern against the right-hand side value. The left-hand side pattern can be a literal, a variable, or a complex pattern consisting of literals, variables, and other patterns.

The following are examples of pattern matching:

```elixir x = 42 # matches 42 {a, b, c} = {:hello, "world", 42} # matches the tuple {:hello, "world", 42} [a, b | tail] = [1, 2, 3, 4, 5] # matches the list [1, 2, 3, 4, 5] and binds a to 1, b to 2, and tail to [3, 4, 5] ^a = 42 # matches 42 if a has the value 42, otherwise raises an error ```

Pattern Types[edit]

Elixir provides various types of patterns to match against different data structures. These patterns include:

Literal Patterns[edit]

Literal patterns match specific values. They can be atoms, integers, floats, booleans, or strings.

Variable Patterns[edit]

Variable patterns start with an uppercase letter or an underscore (_). They match any value and bind the matched value to the variable.

Tuple Patterns[edit]

Tuple patterns match against tuples of a specific size. They can include literals, variables, or other patterns.

List Patterns[edit]

List patterns match against lists of any size. They can include literals, variables, or other patterns.

Map Patterns[edit]

Map patterns match against maps. They can include literals, variables, or other patterns to match map keys and values.

Pattern Matching in Function Clauses[edit]

Pattern matching is commonly used in function definitions. Different function clauses can be defined with different patterns, allowing the function to behave differently based on the arguments provided.

```elixir defmodule Math do

 def add(a, b) do
   IO.puts("Adding two numbers...")
   a + b
 end
 def add([a, b | tail]), do: IO.puts("Adding a list...") a + b + length(tail)

end ```

Benefits of Pattern Matching[edit]

Pattern matching has several benefits in Elixir:

- Simplifies data manipulation and extraction. - Makes code more readable and expressive. - Facilitates pattern-based dispatching in function clauses. - Enables code reuse and maintainability.

Conclusion[edit]

Pattern matching is a powerful feature in Elixir that enables developers to extract, manipulate, and bind variables to different parts of data structures. By leveraging the syntax and various pattern types, developers can write expressive and maintainable code. Learn more about pattern matching in Elixir by exploring the relevant articles on this wiki.

See Also[edit]

References[edit]

<references />