Associative array/Iteration: Difference between revisions

Content added Content deleted
(Added Algol 68)
(→‎{{header|Babel}}: Updated to interactive-mode syntax)
Line 227: Line 227:
=={{header|Babel}}==
=={{header|Babel}}==


In Babel, associative arrays are referred to as maps. To create a map from a list-of-lists:
Use the entsha (mnemonic: "get entries from the hash") operator to obtain a list of all entries, where each entry consists of a 3-element list containing the hashed-key, the key and the value in that order.


<lang babel>births (('Washington' 1732) ('Lincoln' 1809) ('Roosevelt' 1882) ('Kennedy' 1917)) ls2map ! <</lang>
<lang babel>((main
{ (('foo' 12)
('bar' 33)
('baz' 42))
mkhash !


To iterate over a map, in the primary sense, use the overmap utility. We will copy the map (cp operator) so as not to modify the original:
entsha
dup
{1 ith nl <<} each


<lang babel>births cp dup {1 +} overmap !</lang>
"-----\n" <<


To see the results, use the valmap operator:
{2 ith %d nl <<} each})


<lang babel>valmap ! lsnum !</lang>
(mkhash
{ <- newha ->
{ <- dup ->
dup 1 ith
<- 0 ith ->
inskha }
each }))</lang>


This program generates the following
{{out}}
{{out}}
<pre>( 1918 1733 1883 1810 )</pre>
<pre>foo
baz
bar
-----
12
42
33</pre>


There are many ways to interact with a map in Babel. Most of these begin by converting the map to a list or list-of-lists. To look up a list of specific values from the map, by key, use the lumapls utility:
Note that the entsha operator does not return the entries of the hash in any particular order. In general, there is no automatic way to recover the order in which the entries were inserted into the hash.

<lang babel>births ('Roosevelt' 'Kennedy') lumapls ! lsnum !</lang>

{{out}}
<pre>( 1882 1917 )</pre>

To convert the entire map back to a list of key-value pairs:

<lang babel>births map2ls !</lang>

To view the list:

<lang babel>{give swap << " " << itod << "\n" <<} each</lang>

{{out}}
<pre>Kennedy 1917
Washington 1732
Roosevelt 1882
Lincoln 1809</pre>

To merge two maps together, use the mapmerge utility:

<lang babel>foo (("bar" 17) ("baz" 42)) ls2map ! <
births foo mergemap !</lang>

To view the results:

<lang babel>births map2ls ! {give swap << " " << itod << "\n" <<} each</lang>

{{out}}
<pre>baz 42
Kennedy 1917
bar 17
Washington 1732
Roosevelt 1882
Lincoln 1809</pre>

For more information on maps in Babel, view [https://github.com/claytonkb/clean_babel/blob/master/std.sp std.sp] (see the section titled "map utilities").


=={{header|BASIC256}}==
=={{header|BASIC256}}==