Elixir Maps
Elixir Maps[edit]
![](/images/b/b5/Elixir-logo.png)
In Elixir, a map is a data structure that allows you to store key-value pairs. It is similar to dictionaries or hashmaps in other programming languages. Maps are an essential part of Elixir and are used extensively in various scenarios.
Creating Maps[edit]
Maps can be created in Elixir using the `%{}` syntax:
```elixir map = %{:name => "John", :age => 30} ```
Alternatively, you can use the shorthand syntax for atom keys:
```elixir map = %{name: "John", age: 30} ```
Accessing Values[edit]
Once you have created a map, you can access its values using the `.` dot notation or the `Map.get/2` function:
```elixir name = map.name age = Map.get(map, :age) ```
Updating Maps[edit]
Maps in Elixir are immutable, meaning that they cannot be modified once created. However, you can create a new map with updated values using the `Map.put/3` function:
```elixir new_map = Map.put(map, :age, 31) ```
Map Pattern Matching[edit]
Elixir provides a powerful pattern matching feature that allows you to destructure maps and extract specific values:
```elixir %{name: name, age: age} = map ```
Map Functions[edit]
Elixir provides various functions to work with maps, including `Map.keys/1`, `Map.values/1`, and `Map.merge/2`. These functions can be used to manipulate and transform maps in different ways.
Map Enumerables[edit]
Maps in Elixir also support the Enumerable protocol, which means you can use functions like `Enum.map/2`, `Enum.filter/2`, and `Enum.reduce/3` on them.
Examples[edit]
Here are some examples that demonstrate the usage of maps in Elixir:
```elixir user = %{name: "Alice", age: 25, email: "[email protected]"} IO.inspect(user)
%{name: name} = user IO.puts(name)
new_user = Map.put(user, :age, 26) IO.inspect(new_user)
user_list = [user, new_user] IO.inspect(Enum.map(user_list, &(&1.name))) ```
Conclusion[edit]
Maps are a fundamental data structure in Elixir, allowing you to store and manipulate key-value pairs. They are versatile and provide various functions to work with them efficiently. Understanding how to create, access, and update maps is crucial for effective Elixir programming.