Hacker News new | ask | show | jobs
by grantjpowell 2102 days ago
Elixir has a few forms of updating a struct (or map)

    %{existing_map_or_struct | some_key_1: :some_val, some_key_2: :some_val}
Then there is also `put_in/2`, `put_in/3`, `update_in/2`, `update_in/3`, these are nice because they work in pipelines

   some_val
   |> put_in([:foo, :bar, :baz], 3)


   some_val
   |> update_in([:foo, :bar, :baz], fn x -> x + 1 end)
The macro forms are cool too

   put_in(foo.bar.baz, 2)

   update_in(foo[:some]["nested"][:path], & &1 + 1)
The cool thing about the `/2` forms of `put_in` and `update_in` is that they are macros they rewrite the ast to return the entire object, and not just the changed value.

    iex(1)> foo = %{bar: %{baz: 2}}
    %{bar: %{baz: 2}}

    iex(2)> update_in(foo.bar.baz, & &1 + 1)
    %{bar: %{baz: 3}}
There's even more powerful macros like `get_and_update_in` which can use "selectors" to extend their functionality (https://hexdocs.pm/elixir/master/Kernel.html#get_and_update_...)

https://hexdocs.pm/elixir/master/Kernel.html#put_in/2

https://hexdocs.pm/elixir/master/Kernel.html#put_in/3

https://hexdocs.pm/elixir/master/Kernel.html#update_in/2

https://hexdocs.pm/elixir/master/Kernel.html#update_in/3