unexpected semantics with using lists as default elements in tables
- From: Jan <storkchen@xxxxxxxxx>
- Date: Tue, 22 Jun 2010 08:23:13 -0700 (PDT)
Dear Icon friends,
I have been using Icon for more than 20 years now, and I love it, but
every now and then I run into this strange little oddity with tables
and default elements. I will illustrate what I mean with a very short
and simple program:
link ximage
procedure main()
T := table([])
put(T["A"],1) # I want to add 1 to the empty list that is defined
for as-yet-nonexistent entry "A"
put(T["B"],2) # and 2 to the empty list for nonexistent entry "B"
write(ximage(T))
end
What I expect now as output is this:
T1 := table({L1 := list(0)
L1})
T1["A"] := L2 := list(1)
L2[1] := 1
T1["B"] := L3 := list(1)
L3[1] := 2
Because I added elements 1 and 2 to the default element [] that should
exist for the (newly created) entries for keys "A" and "B". However,
what I get is this:
T1 := table({L1 := list(2)
L1[1] := 1
L1[2] := 2
L1})
This is a table with NO entries in it, and default element [1,2]. In
other words, the 1 and 2 are added to the default element, causing it
to change.
This is unfortunate, and probably a consquence of lists not being
copied but passed by reference in the impementation. Because with
integers, it *does* work as expected. The classical program used for
counting things works this way:
link ximage
procedure main()
T := table(0) # now the default element is an integer
T["A"] +:= 10
T["B"] +:= 11
write(ximage(T))
end
and this does result in the expected and desired behavior, namely
T1 := table(0)
T1["A"] := 10
T1["B"] := 11
and NOT in
T1 := table(21)
which would be the equivalent to what happens in the list example.
For lists, there is a "workaround", if I initialize the new table
entries by hand
procedure main()
T := table([])
T["A"] := []
T["B"] := []
...
but that feels a bit silly. After all, they should already BE an empty
list, because of the default.
Anyone else ran into this one? Is this fixable without too much
trouble in the implementation? I'd be happy to hear your comments
about this.
Cheers,
Jan
.
- Follow-Ups:
- Prev by Date: Re: Icon Programming Language FAQ
- Next by Date: Re: unexpected semantics with using lists as default elements in tables
- Previous by thread: Re: Icon Programming Language FAQ
- Next by thread: Re: unexpected semantics with using lists as default elements in tables
- Index(es):
Relevant Pages
|