From: Lars H. <Lar...@re...> - 2008-12-07 16:34:47
|
Donal K. Fellows skrev: > Lars Hellström wrote: >> The *dict* command will get a new subcommand *dict >> getwithdefault* /dictionary/ /key/ ?/key/ ...? /value/ > > Now the questions: > 1) Which is best: "getwithdefault" vs. "getdefault"? I too agree with Twylite that a separate verb is better than a multiword phrase (although changing the subcommand name can be done at the script level, so it wouldn't be a catastrophe to have ::tcl::dict::getwithdefault as the underlying command). "lookup" to me signals some more advanced behaviour for missing keys than just returning a constant, so I suppose I would prefer "fetch", but for the rest of this mail I'm sticking with "getwithdefault". > 2) Should the default value be before or after the keys? My argument for putting it after has been analogy with [dict set]: dict set D key1 key2 value dict getwithdefault $D key1 key2 value It also has the effect that key and value occur in the same order as in the string representation: dict getwithdefault {-foo bar} -foo baz In addition, one could claim an analogy with [dict replace]: dict replace $D -foo bar dict getwithdefault $D -foo bar Conversely, I don't think there is any [dict] subcommand which puts a key after its value. > 3) Is a zero-length key list meaningful? (cf TIP#323) The zero-length key list is not supported by [dict exists], and only supported by [dict get] as a special case (return corresponding key--value list). It doesn't make sense when the number of keys is fixed -- dict getwithdefault $D $default would always return $D and never $default -- so what remains is the case of variable-length paths: dict getwithdefault $D {*}$path $default The question is, what kind of $default would make sense in such a case? If the same default is valid as an entry in a dictionary and for the dictionary as a whole, it follows that this entry is itself a dictionary of the same type as the whole, i.e., the dictionary is some kind of tree. The binary search tree 0=A / \ / \ / \ -1=@ 2=C / / 1=B /might/ indeed get encoded with nested dictionaries as key 0 value A left {key -1 value @} right {key 2 value C left {key 1 value B}} so /maybe/ it could make sense, but I'm having trouble imagining an algorithm that would benefit from the combination of a possibly zero-length $path and a default for missing nodes. In the case of a nested-dictionaries tree, I can however imagine it useful to retrieve an arbitrary node using a $path. Since that in the case of the root would cause [dict get] to return a list rather than a dictionary, shimmering might follow, so maybe that is a use-case for [dict getwithdefault $D {*}{} notused]. It's quite a stretch, though. Lars Hellström |