Do we really need nil values in maps?

Yeah, just to be clear. Map.put/3 simply calls map:put/3. The rationale for not allowing %{some_map | new_key: :foo} I suppose is related to structs, such that it should blow up with a KeyError if the key does not exist (i.e., you more than likely made a mistake).

2 Likes

I guess one thing I’m very confused on here… what is putting nil values in your maps that you don’t have control over?

2 Likes

Hi.
It’s not about control, nor about ambiguities. Both the Erlang and elixir way work when one understands the semantics. No problem there.

My problem is simply that there is no (built-in) way in declarative syntax to “omit” a value on a condition - which would make it immediately more helpful for my usage scenario.

In elixir nil takes a special role as value returned by the API indicating often “no value.” It was my misunderstanding this special role of nil also occurred in Erlang. But the code I presented and looked at actually had no special role for nil, it merely accepted nil like any other value as valid and hence would consider any key with value nil as present. (Technically, half of elixir’s API does so, too, which could be considered inconsistent.) So the conclusion would be on my side, at this point, that the problem is not the role of nil, at least not in Erlang.

The problem is simply that neither Erlang nor elixir offer a way to define a map in declarative syntax while saying “only add this value if” semantically. Since expressions always have to evaluate to something, this would have probably been needed to be included at the syntax level already or a special value could have been defined to mean “omit.”

That’s the gist of it.

4 Likes

Enum.flat_map/2 is a good idea, but it can be risky. I’m not entirely sure how the flattening in this function is implemented, but for example List.flatten/1 is recursive. And the structures contain lists and possible lists of lists.

On the other hand, using [] (ironically, also called “nil” as OverMindDL1 mentioned) might in some cases work better than nil, it depends.

3 Likes

Gotcha, I was just making sure there wasn’t a problem you were facing, like maybe your ending up with nils in your maps because per decoding json.

I get you’re just wanting to have a discussion on the merits of having a declarative syntax, just wanted to be doubly sure there wasn’t a problem problem :slight_smile:

4 Likes

Are there any other languages that let you do what you want?

3 Likes