r/ProgrammingLanguages • u/Inconstant_Moo š§æ Pipefish • Jul 24 '26
Requesting criticism Default values in maps?
We often find a case where we'd like to e.g. count the occurrences of a word in a piece of text. We would like to be able to write this so the main body of our loop says count[word] = count[word] + 1. Except that if count[word] hasn't been initialized as 0 at some point then you have do that or typically this will be a runtime error.
Or the language can try and let you do that, e.g. Golang would actually return 0, because this is the designated "zero value" to return when you index into a map with integer values and the key isn't there.
Which is great for the case I described in the first paragraph, but in the more general case we want a runtime error when we do something stupid, and in other cases trying to index a map by a nonexistent key often is stupid.
This is especially so in Pipefish, a relatively dynamic language, where normally there are no compile-time constraints even on the type of your key and you may have messed up big-time. If we took the Golang approach, then if you indexed your list of words by 42 or false you'd still get 0 instead of an error. So we don't do that: Pipefish is hardass about this and throws a runtime error over the missing key to compensate for letting you play fast-and-loose with types.
But this dynamism around types gives us an easy way to make default values for maps. Let's define a builtin type default with one element DEFAULT, and make the compiler/VM treat that as one more magic type like error and tuple.
Then our word-counting function could be written like this:
count(words list) -> map :
from M = map(DEFAULT::0) for _::word = range words :
M with word:: M[word]+1Since DEFAULT is just a normal value apart from when we index maps, we could easily sanitize this on the way out of the function:
count(words list) -> map :
undefault from M = map(DEFAULT::0) for _::word = range words :
M with word:: M[word]+1
undefault(M map) :
M without DEFAULTNow, I hesitate over adding this because Pipefish is meant to be small and simple and I worry about adding even one feature. But on the other hand it seems like the use-case is common and the semantics are simple and it satisfies the other core principle of Pipefish --- that I should have my cake and eat it.
23
u/WittyStick Jul 24 '26
I'd like to see
upsertin more APIs.21
u/__dict__ Jul 24 '26
Python has dict, which throws on indexing to a non-existent key. But it also has defaultdict in a library that's just a subclass that let's you set the default value.
19
u/matthieum Jul 24 '26
The Rust Entry API was added specifically to allow a single look-up and then an action on presence & absence.
In your case, it would be a matter of
*map.entry(word).or_default() += 1;.Java similarly has a bunch of different methods
computeIfPresent,putIfAbsent, etc... which means a lot more API surface, but the same guiding principle: be explicit about your intention.5
u/Ninesquared81 Victoria Jul 24 '26
You may be interested in Python's defaultdict, which achieves the same end goal. In Python's case,
defaultdictis a subclass of the normaldictclass, which is probably the right way to go about it.You might also be interested in Odin's or_else, which can be used to achieve a similar thing in a more general way. Something like
m[word] = (m[word] or_else 0) + 14
u/TheChief275 Jul 24 '26
This is why I think a find is always better than indexing syntax. C++ std ran into this problem as well and decided the best fix would be to insert instead of failing. With a find you can do this instead:
Or instead have an insert that internally always finds an entry first before trying to add (my preference). You need someway to know if it actually added. You can also have a special method that does this for you; something like "insert_or_default"
4
u/ap29600 Jul 24 '26
k has a special form
amendfor arrays and dictionaries which is used for modified assignment:a[i] +: bdesugars toa : @[a; i; +; b]wherein the operation+is passed to the 4-argument amend function@this has the semantics of returning a new structure that is equivalent to a, except that it hasa[i]+bat positioni. the benefit of this is that the indexing is part of the logic ofamend, which also knows what operation is being used. it checks the identity element for the operator+and determines that it is0, so in the case of missing keys it uses that value. every primitive operator has default values for each type, which act as identity elements for those that have them and sensible defaults for those that don't. here they are for integersif the operator used is not arithmetic (which can happen because k has many non arithmetic operators, all of which work in modified assignment) then the null element for the appropriate type is used
3
u/MichalMarsalek Jul 24 '26
In my WIP language, functions and maps are just one thing. You can do
or
or combine the two and do
But this is a kind of core behaviour of the language, not something easily adaptible to other languages.
1
u/esotologist Jul 24 '26
C# let's you override the indexer so you could have it return a default or null or throw based on preferenceĀ
1
u/busres Jul 24 '26 edited Jul 24 '26
Mesgjs lists support this.
#is the local storage object (a list instance);[...]is a list literal;object(op...)is a message.#wordis sugar for#(at word), and#[count #word else=0]is sugar for#(at count #word else=0), so you could say#(set count #word to=#[count #word else=0])(+ 1)).1
u/ScottBurson Jul 24 '26
My FSet library for Common Lisp has this feature.
1
u/kwan_e tonal-lang Jul 25 '26
I personally would be looking at policy-based design. Whether the policy is part of the map type, or a runtime argument on construction.