Home Posts Post Search Tag Search

Kernel put_in/3 update_in/3 and anonymous
Published on: 2025-04-03 Tags: Agents, Kernel, anonymous

So I wanted to go over a couple built-in functions that really helped me increase the legibility of my code.

put_in/3: this is used to add in a key pair within a map, update_in/3 this is used to update a key pair within a map… So what is the big deal we have Map.put and Map.update…

put_in and update_in can use paths. This turns a nested Map.put into a single function call.

They follow a syntax as follows: put_in(data, keys, value) Where data can be as deep into a nested map as you want. users = %{“john” => %{age: 27}, “meg” => %{age: 23}} put_in(users, [“john”, :age], 28)

You can even change the value into a function, while using the update_in/3.

Now let’s talk about Anonymous functions, because you can add in an anonymous function to the update_in/3

update_in(users, [“jane”, :age], &(&1 + 1)) Lets break this down &(..) is setting up an anonymous function &1 takes the first argument +1 will add one

You can even use this to add an item to a list &([new_item | &1]

Try to use these new functions to add more clean code to your elixir code.