programming - Is there a practical way to define a default value for missing keys in an Association?
Clarification
Although I may be missing his point I currently feel that Leonid's comments below are misleading. I am not looking for anything that is not already a part of Association
functionality other than a way to define what is returned for a missing key on a per-association basis. I thought that the Block
example below made this clear but perhaps not.
I am seeking a way to do something like this:
asc = <|"a" -> 1, "b" -> 2, _ -> 0|>;
asc["x"]
(* desired output: 0 *)
(* actual output: Missing["KeyAbsent", "x"] *)
Critically I am not looking for general pattern matching of Key names however; I only want a way to define one default value for missing keys.
Original ramblings
It can be very useful to define background or default value for an object that can be incremented or otherwise modified. A simple (and for me, common) use is a counter:
count[_] = 0;
++count[#] & /@ {"a", "a", "b", "a", "b", "a"}
{1, 2, 1, 3, 2, 4}
Since there are advantages to Association
such as ease of copying and direct manipulation of keys and values I would like to port this method to new function. However I cannot think of a clean, practical way to define a default. (I consider directly overloading System functions such as Increment
undesirable.)
I note that it is possible to increment a missing value and then clean it up afterward:
asc = <||>;
++asc[#] & /@ {"a", "a", "b", "a", "b", "a"} /. _Missing -> 0
{1, 2, 1, 3, 2, 4}
This isn't really the same as setting a default value however and it limits the way this method can be used. Somewhat better I think is to temporarily redefine Missing
. This at least gives values that are up-to-date while the operation is performed.
asc = <||>;
Block[{Missing},
Missing["KeyAbsent", _] = 0;
++asc[#] & /@ {"a", "a", "b", "a", "b", "a"}
]
asc
{1, 2, 1, 3, 2, 4}
<|"a" -> 4, "b" -> 2|>
This could be packaged a bit more nicely but it still feels like a bit of a kluge.
Is there an approach I am failing to consider? Or by some slim chance is there a hidden way to do this?
Comments
Post a Comment