Maps_in - An Erlang library to handle nested maps

Hello!

maps_in is a library to handle nested maps. It contains almost the same functions as the standard maps module, the difference is that the key is always a list, for example:

get/2

1> Map = #{my => #{nested => map}}.
#{my => #{nested => map}}
2> maps_in:get([my, nested], Map).
map

put/3

1> Map = #{my => #{more => #{deep => #{}}}}.
#{my => #{more => #{deep => #{}}}}
2> maps_in:put([my, more, deep], #{nested => map}, Map).
#{my => #{more => #{deep => #{nested => map}}}}

update_with/3

1> Map = #{someone => #{age => 17}}.
#{someone => #{age => 17}}
2> maps_in:update_with([someone, age], fun(Age) -> Age + 1 end, Map).
#{someone => #{age => 18}}

I was facing some trouble creating dynamic functions using maps in Zotonic templates, so I decided to create this helper library.
The _in functions family from Elixir Kernel (get_in, put_in, update_in, etc.) was the lib name’s inspiration.

List of functions:

It’s also available in hex.

If you find some of the functions really useful, leave a comment and maybe a proposal for the OTP lib can be made.

Feels free to contribute o/

Note: docs and tests should be improved.

13 Likes

This reminds me of of some Clojure libs, which is likely where the Elixir people got their inspiration.

2 Likes

I also have something similar since a while back, that we’ve used extensively in production: mapz — mapz v2.3.0

The reason for the naming (functions prefixed with deep_... is that I envisioned it at some point being included in the real maps module in OTP :slight_smile:

Fun to see more alternatives in this space!

2 Likes

Very nice :slight_smile:

I must have written these accessor and merge functions about half a dozen times by now, good to see them in libraries.

2 Likes

Oh! I didn’t know about your lib. So this is not just my need. IMO these functions are good stuff to be in the standard lib (at least the main ones).

1 Like

Yeah, didn’t exactly advertise it (probably should have, and sorry for hijacking your thread).

I only implemented the functions that I really needed in production over time, as I went. And I tried to keep the naming, argument order and errors as close to the maps module as possible.

2 Likes

You’re not hijacking. I really appreciate your comments and your lib. Even so, I will continue to improve the maps_in docs and tests when possible, because, currently, I’m a little busy.

2 Likes