Hi all,
I've stumbled about this puzzling and seemingly simple task: Iterate
over a a bundle and print the key-value pairs.
Here a simple example:
<hansl>
bundle B = _(a = 1, b = 2)
loop foreach i B
printf "key: %s, value: %d\n", "$i", $i
# OR: printf "key: $i, value: %d\n", , $i
endloop
</hansl>
That works as all elements in B are numeric.
However, I always found this confusing: For the first printf, the key is
accessed by means of "$i" as an argument while in the second line one
accesses it via $i inside the 'format' part.
ALSO NOTE: The parser is "robust" against the two comma at the end of
the second printf command. Bug or feature? ;-)
But lets augment the bundle and add a third string object. HOW TO,
iterate in this case across the bundle _without_ having to check the
data type? Is there such a way? The following fails.
<hansl>
string B.c = "foo"
B
loop foreach i B
# FAILS AS value linked to "c" is of type string: printf "key: %s,
value: %d\n", "$i", $i
# ALSO FAILS: printf "key: $i, value: %d\n", $i
endloop
</hansl>
In Julia, similar to Python, a loop over a dictionary constructs two
separate variables: one for the key and another one for the value so
it's simple to remember on how to access the key or bundle.
<Julia>
for (k,v) in d
println("key: $k, value: $v")
end
</Julia>
I am wondering whether this is a side-product of these languages such
that k or v can take every data type on-the-fly.
Of course, I know that we don't have that. But I just wanted to mention
that it feels like a solid approach for printing key-value pairs.
Oh, here is another issue which I do not understand:
<hansl>
bundle B = _(a = 1, b = 2)
loop foreach i B
eval B["$i"] # print value works
printf "key: %i, value: %d\n", B["$i"] # FAILS: "Syntax
error"
endloop
</hansl>
Thanks,
Artur