V2 - Map Lookup Fallback / Test + Lookup

Propose new features and changes
User avatar
Coiler
Posts: 114
Joined: 29 Nov 2020, 09:06

V2 - Map Lookup Fallback / Test + Lookup

31 Dec 2020, 11:11

Currently, one needs to use my_map.Has(key) if the programmer is unsure of a key being in the map or not. However, I'm pretty sure the internal code for Has() most likely needs to do a full key search to return the answer. And almost certainly, the programmer is going to have code that looks like this:

Code: Select all

if( my_map.Has(my_key) )
	my_var := my_map[my_key]
This means the lookup is done twice for every lookup, when uncertain. I propose a new ability to safely scope out map elements and obtain their value at the same time when they exist. If I were developing the system, I would also add (any/all of) the following features to map objects:
  • A safe map.Get(my_key,my_default) function that returns the user's default value when the key doesn't exist.
  • A map.SetIfMissing(my_key,my_value) type function that only assigns the value if the key doesn't exist (probably with a better function name).
  • A map.GetSet(my_key,start_value) type function that assigns start_value only when the key doesn't exist, then returns the current key value afterward.
Thanks for reading my wishes!
HotKeyIt
Posts: 2364
Joined: 29 Sep 2013, 18:35
Contact:

Re: V2 - Map Lookup Fallback / Test + Lookup

31 Dec 2020, 12:21

You can use try

Code: Select all

my_key:="anykey"
my_map:=Map()
try my_var := my_map[my_key]
catch
  my_var:="default"
MsgBox my_var
In AutoHotkey_H you can use DefineDefault:

Code: Select all

my_key:="anykey"
my_map:=Map().DefineDefault("default")
my_var := my_map[my_key]
MsgBox my_var
User avatar
nnnik
Posts: 4500
Joined: 30 Sep 2013, 01:01
Location: Germany

Re: V2 - Map Lookup Fallback / Test + Lookup

09 Jan 2021, 07:23

Using try is really an antipattern in this case.
I would suggest the following function names (taken from https://docs.oracle.com/javase/8/docs/api/java/util/Map.html)
map.Get(my_key,my_default)->map.getOrDefault(my_key,my_default)
map.SetIfMissing(my_key,my_value)->map.computeIfMissing(my_key, callable)

Also I don't think a map needs to throw if an entry is accessed that is missing.
Neither Java nor javascript throw if an entry is accessed that doesn't exist.
Weirdly Python does throw if you use the [] syntax but doesn't throw if you use get.
Perhaps instead of addig these weird workarounds we should add an access method that doesn't throw.
Recommends AHK Studio

Return to “Wish List”

Who is online

Users browsing this forum: ntepa and 51 guests