elixir map

Elixir Map

In Elixir, a map is a data structure that stores key-value pairs. It is similar to a dictionary or an associative array in other programming languages. Maps are defined using the %{} syntax, where keys and values are separated by =>. Here's an example of a map in Elixir:

map = %{name: "John", age: 30, city: "New York"}

To access the value associated with a specific key in a map, you can use the dot notation or the square bracket notation. Here are examples of both:

name = map.name
age = map[:age]

To update a value in a map, you can use the Map.put/3 function. It takes the map, the key, and the new value as arguments and returns a new map with the updated value. Here's an example:

new_map = Map.put(map, :age, 31)

To add a new key-value pair to a map, you can use the Map.put_new/3 function. It works similarly to Map.put/3, but it only adds the key-value pair if the key doesn't already exist in the map. Here's an example:

new_map = Map.put_new(map, :city, "Los Angeles")

To remove a key-value pair from a map, you can use the Map.delete/2 function. It takes the map and the key as arguments and returns a new map without the specified key-value pair. Here's an example:

new_map = Map.delete(map, :age)

It's important to note that maps in Elixir are immutable, which means that any operation on a map will return a new map without modifying the original one.