gracelang / language

Design of the Grace language and its libraries
GNU General Public License v2.0
6 stars 1 forks source link

Dictionary lacks at(_)ifPresent(_)ifAbsent(_) #125

Open apblack opened 7 years ago

apblack commented 7 years ago

Occasionally, such as when searching through a stack of dictionaries, it's necessary to "keep going" if the key is not found, and to return if the key is found.

at(_)ifAbsent(_)makes it easy to do the opposite, but it's clunky to do what's necessary.

method find(key) in (dictionaries) {
    for (dictionaries) do { dict ->
         def found := true
         def value = dict.at(key) ifAbsent { found := false }
        if (found) then { return value }
    }
     NotFound.raise "key {key} was not found in any of the dictionaries"
}

With the proposed method, this code cleans up nicely:

method find(key) in (dictionaries) {
    for (dictionaries) do { dict ->
         dict.at(key) isPresent { value -> return value }  ifAbsent { }
    }
     NotFound.raise "key {key} was not found in any of the dictionaries"
}

This is based on an actual example in the gradual type checker.