usethesource / rascal

The implementation of the Rascal meta-programming language (including interpreter, type checker, parser generator, compiler and JVM based run-time system)
http://www.rascal-mpl.org
Other
394 stars 77 forks source link

Get function for maps with default value #1910

Closed linuswagner closed 4 months ago

linuswagner commented 4 months ago

Is your feature request related to a problem? Please describe. Sometimes, we cannot guarantee that a key exists for a map, but instead of raising an error, we want to work on a default value (imagine having a map where you have counted the occurrence of words. If a word does not exist in the map, that means that its count is 0). Currently, we have to write something like

someValue = 0;
if (someKey in someMap) {
   someValue = someMap[someKey];
}

which is quite lengthy.

Describe the solution you'd like Other languages defines a get method for map-like structures where there is an optional argument that is the return value of the function if the key in the map cannot be found. Would be helpful to have it as well in Rascal. This reduces the example above to

someValue = get(someMap, someKey, 0)

The last parameter should be optional, such that get(someMap, someKey) behaves the same as someMap[someKey].

Describe alternatives you've considered n.a.

Additional context n.a.

mahills commented 4 months ago

Does this not work anymore? https://www.rascal-mpl.org/docs/Rascal/Expressions/Values/Boolean/IfDefinedElse/

someValue = someMap[someKey] ? 0;
linuswagner commented 4 months ago

It does, thanks @mahills

mahills commented 4 months ago

Ok, I'm glad that works!