Sujet : Re: Array get element with default (no error if not exist)
De : emil.g (at) *nospam* example.invalid (Emiliano)
Groupes : comp.lang.tclDate : 16. Aug 2024, 15:16:04
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20240816111604.6e47340154e68f982aa12c3f@example.invalid>
References : 1
User-Agent : Sylpheed 3.7.0 (GTK+ 2.24.33; x86_64-pc-linux-gnu)
On Fri, 16 Aug 2024 07:10:30 +0000
RodionGork <
rodiongork@github.com> wrote:
Hi Friends!
Still making my first feeble steps in TCL so please excuse me if this is
naive or was asked multiple times.
Attempt to fetch by non-existing key in "associative array" results in
error, e.g.
set a(1) 5
puts $a(2) ;# yields error
the workaround seems to be [info exists ::a(2)] which feels a bit remote
from other "array" commands.
Is there some motivation why some command for get-with-default is not
implemented, e.g.
puts [array peek $a 2 "default value"]
Popular use-case for this would be creating map where elements are
updated (like counter of words etc) - though I found this is cleverly
covered by "incr" and "append" commands properly behaving
when element to be incremented or appended does not exist yet.
But I suspect there are other situations when such a command may be
handy.
Already there in 8.7/9.0
% array default set foo NOSUCHVALUE
% set foo(1)
NOSUCHVALUE
% info exists foo(1)
0
8.7/9.0 also adds [dict getwithdefault] (aka [dict getdef]) for dict
values.
Also why [array exists ...] command does not exist (while [dict exists
..] does)? Perhaps there is something about no good syntax for it due
to how arrays are implemented?
The [array exists] command is there since ... forever
% array exists foo
1
% array exists nosucharray
0
Well, at least since 8.4 . See
https://www.tcl-lang.org/man/tcl8.4/TclCmd/array.htm-- Emiliano