2016 Update
This commit is contained in:
parent
948b86eafa
commit
dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions
|
|
@ -1,6 +1,7 @@
|
|||
Show how to iterate over the key-value pairs of an associative array,
|
||||
and print each pair out.
|
||||
Also show how to iterate just over the keys, or the values,
|
||||
if there is a separate way to do that in your language.
|
||||
Show how to iterate over the key-value pairs of an associative array, and print each pair out.
|
||||
|
||||
Also show how to iterate just over the keys, or the values, if there is a separate way to do that in your language.
|
||||
|
||||
|
||||
{{Template:See also lists}}
|
||||
<br><br>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,155 @@
|
|||
# associative array handling using hashing #
|
||||
|
||||
# the modes allowed as associative array element values - change to suit #
|
||||
MODE AAVALUE = STRING;
|
||||
# the modes allowed as associative array element keys - change to suit #
|
||||
MODE AAKEY = STRING;
|
||||
# nil element value #
|
||||
REF AAVALUE nil value = NIL;
|
||||
|
||||
# an element of an associative array #
|
||||
MODE AAELEMENT = STRUCT( AAKEY key, REF AAVALUE value );
|
||||
# a list of associative array elements - the element values with a #
|
||||
# particular hash value are stored in an AAELEMENTLIST #
|
||||
MODE AAELEMENTLIST = STRUCT( AAELEMENT element, REF AAELEMENTLIST next );
|
||||
# nil element list reference #
|
||||
REF AAELEMENTLIST nil element list = NIL;
|
||||
# nil element reference #
|
||||
REF AAELEMENT nil element = NIL;
|
||||
|
||||
# the hash modulus for the associative arrays #
|
||||
INT hash modulus = 256;
|
||||
|
||||
# generates a hash value from an AAKEY - change to suit #
|
||||
OP HASH = ( STRING key )INT:
|
||||
BEGIN
|
||||
INT result := ABS ( UPB key - LWB key ) MOD hash modulus;
|
||||
FOR char pos FROM LWB key TO UPB key DO
|
||||
result PLUSAB ( ABS key[ char pos ] - ABS " " );
|
||||
result MODAB hash modulus
|
||||
OD;
|
||||
result
|
||||
END; # HASH #
|
||||
|
||||
# a mode representing an associative array #
|
||||
MODE AARRAY = STRUCT( [ 0 : hash modulus - 1 ]REF AAELEMENTLIST elements
|
||||
, INT curr hash
|
||||
, REF AAELEMENTLIST curr position
|
||||
);
|
||||
|
||||
# initialises an associative array so all the hash chains are empty #
|
||||
OP INIT = ( REF AARRAY array )REF AARRAY:
|
||||
BEGIN
|
||||
FOR hash value FROM 0 TO hash modulus - 1 DO ( elements OF array )[ hash value ] := nil element list OD;
|
||||
array
|
||||
END; # INIT #
|
||||
|
||||
# gets a reference to the value corresponding to a particular key in an #
|
||||
# associative array - the element is created if it doesn't exist #
|
||||
PRIO // = 1;
|
||||
OP // = ( REF AARRAY array, AAKEY key )REF AAVALUE:
|
||||
BEGIN
|
||||
REF AAVALUE result;
|
||||
INT hash value = HASH key;
|
||||
# get the hash chain for the key #
|
||||
REF AAELEMENTLIST element := ( elements OF array )[ hash value ];
|
||||
# find the element in the list, if it is there #
|
||||
BOOL found element := FALSE;
|
||||
WHILE ( element ISNT nil element list )
|
||||
AND NOT found element
|
||||
DO
|
||||
found element := ( key OF element OF element = key );
|
||||
IF found element
|
||||
THEN
|
||||
result := value OF element OF element
|
||||
ELSE
|
||||
element := next OF element
|
||||
FI
|
||||
OD;
|
||||
IF NOT found element
|
||||
THEN
|
||||
# the element is not in the list #
|
||||
# - add it to the front of the hash chain #
|
||||
( elements OF array )[ hash value ]
|
||||
:= HEAP AAELEMENTLIST
|
||||
:= ( HEAP AAELEMENT := ( key
|
||||
, HEAP AAVALUE := ""
|
||||
)
|
||||
, ( elements OF array )[ hash value ]
|
||||
);
|
||||
result := value OF element OF ( elements OF array )[ hash value ]
|
||||
FI;
|
||||
result
|
||||
END; # // #
|
||||
|
||||
# returns TRUE if array contains key, FALSE otherwise #
|
||||
PRIO CONTAINSKEY = 1;
|
||||
OP CONTAINSKEY = ( REF AARRAY array, AAKEY key )BOOL:
|
||||
BEGIN
|
||||
# get the hash chain for the key #
|
||||
REF AAELEMENTLIST element := ( elements OF array )[ HASH key ];
|
||||
# find the element in the list, if it is there #
|
||||
BOOL found element := FALSE;
|
||||
WHILE ( element ISNT nil element list )
|
||||
AND NOT found element
|
||||
DO
|
||||
found element := ( key OF element OF element = key );
|
||||
IF NOT found element
|
||||
THEN
|
||||
element := next OF element
|
||||
FI
|
||||
OD;
|
||||
found element
|
||||
END; # CONTAINSKEY #
|
||||
|
||||
# gets the first element (key, value) from the array #
|
||||
OP FIRST = ( REF AARRAY array )REF AAELEMENT:
|
||||
BEGIN
|
||||
curr hash OF array := LWB ( elements OF array ) - 1;
|
||||
curr position OF array := nil element list;
|
||||
NEXT array
|
||||
END; # FIRST #
|
||||
|
||||
# gets the next element (key, value) from the array #
|
||||
OP NEXT = ( REF AARRAY array )REF AAELEMENT:
|
||||
BEGIN
|
||||
WHILE ( curr position OF array IS nil element list )
|
||||
AND curr hash OF array < UPB ( elements OF array )
|
||||
DO
|
||||
# reached the end of the current element list - try the next #
|
||||
curr hash OF array +:= 1;
|
||||
curr position OF array := ( elements OF array )[ curr hash OF array ]
|
||||
OD;
|
||||
IF curr hash OF array > UPB ( elements OF array )
|
||||
THEN
|
||||
# no more elements #
|
||||
nil element
|
||||
ELIF curr position OF array IS nil element list
|
||||
THEN
|
||||
# reached the end of the table #
|
||||
nil element
|
||||
ELSE
|
||||
# have another element #
|
||||
REF AAELEMENTLIST found element = curr position OF array;
|
||||
curr position OF array := next OF curr position OF array;
|
||||
element OF found element
|
||||
FI
|
||||
END; # NEXT #
|
||||
|
||||
# test the associative array #
|
||||
BEGIN
|
||||
# create an array and add some values #
|
||||
REF AARRAY a1 := INIT LOC AARRAY;
|
||||
a1 // "k1" := "k1 value";
|
||||
a1 // "z2" := "z2 value";
|
||||
a1 // "k1" := "new k1 value";
|
||||
a1 // "k2" := "k2 value";
|
||||
a1 // "2j" := "2j value";
|
||||
# iterate over the values #
|
||||
REF AAELEMENT e := FIRST a1;
|
||||
WHILE e ISNT nil element
|
||||
DO
|
||||
print( ( " (" + key OF e + ")[" + value OF e + "]", newline ) );
|
||||
e := NEXT a1
|
||||
OD
|
||||
END
|
||||
|
|
@ -0,0 +1 @@
|
|||
births (('Washington' 1732) ('Lincoln' 1809) ('Roosevelt' 1882) ('Kennedy' 1917)) ls2map ! <
|
||||
|
|
@ -0,0 +1 @@
|
|||
births cp dup {1 +} overmap !
|
||||
|
|
@ -0,0 +1 @@
|
|||
valmap ! lsnum !
|
||||
|
|
@ -0,0 +1 @@
|
|||
births ('Roosevelt' 'Kennedy') lumapls ! lsnum !
|
||||
|
|
@ -0,0 +1 @@
|
|||
births map2ls !
|
||||
|
|
@ -0,0 +1 @@
|
|||
{give swap << " " << itod << "\n" <<} each
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
foo (("bar" 17) ("baz" 42)) ls2map ! <
|
||||
births foo mergemap !
|
||||
|
|
@ -0,0 +1 @@
|
|||
births map2ls ! {give swap << " " << itod << "\n" <<} each
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
((main
|
||||
{ (('foo' 12)
|
||||
('bar' 33)
|
||||
('baz' 42))
|
||||
mkhash !
|
||||
|
||||
entsha
|
||||
dup
|
||||
{1 ith nl <<} each
|
||||
|
||||
"-----\n" <<
|
||||
|
||||
{2 ith %d nl <<} each})
|
||||
|
||||
(mkhash
|
||||
{ <- newha ->
|
||||
{ <- dup ->
|
||||
dup 1 ith
|
||||
<- 0 ith ->
|
||||
inskha }
|
||||
each }))
|
||||
|
|
@ -1,18 +1,5 @@
|
|||
defmodule RC do
|
||||
def test_iterate(dict_impl \\ Map) do
|
||||
d = dict_impl.new |> Dict.put(:foo,1) |> Dict.put(:bar,2)
|
||||
print_vals(d)
|
||||
end
|
||||
|
||||
defp print_vals(d) do
|
||||
IO.inspect d
|
||||
Enum.each(d, fn {k,v} -> IO.puts "#{k}: #{v}" end)
|
||||
Enum.each(Dict.keys(d), fn key -> IO.inspect key end)
|
||||
Enum.each(Dict.values(d), fn value -> IO.inspect value end)
|
||||
end
|
||||
end
|
||||
|
||||
IO.puts "< iterate Map >"
|
||||
RC.test_iterate
|
||||
IO.puts "\n< iterate HashDict >"
|
||||
RC.test_iterate(HashDict)
|
||||
IO.inspect d = Map.new([foo: 1, bar: 2, baz: 3])
|
||||
Enum.each(d, fn kv -> IO.inspect kv end)
|
||||
Enum.each(d, fn {k,v} -> IO.puts "#{inspect k} => #{v}" end)
|
||||
Enum.each(Map.keys(d), fn key -> IO.inspect key end)
|
||||
Enum.each(Map.values(d), fn value -> IO.inspect value end)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
myDict := Map with(
|
||||
"hello", 13,
|
||||
"world", 31,
|
||||
"!" , 71
|
||||
)
|
||||
|
||||
// iterating over key-value pairs:
|
||||
myDict foreach( key, value,
|
||||
writeln("key = ", key, ", value = ", value)
|
||||
)
|
||||
|
||||
// iterating over keys:
|
||||
myDict keys foreach( key,
|
||||
writeln("key = ", key)
|
||||
)
|
||||
|
||||
// iterating over values:
|
||||
myDict foreach( value,
|
||||
writeln("value = ", value)
|
||||
)
|
||||
// or alternatively:
|
||||
myDict values foreach( value,
|
||||
writeln("value = ", value)
|
||||
)
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
fun main(a: Array<String>) {
|
||||
val map = mapOf("hello" to 1, "world" to 2, "!" to 3)
|
||||
|
||||
with(map) {
|
||||
forEach { println("key = ${it.key}, value = ${it.value}") }
|
||||
keys.forEach { println("key = $it") }
|
||||
values.forEach { println("value = $it") }
|
||||
}
|
||||
}
|
||||
|
|
@ -1,57 +1,55 @@
|
|||
/*REXX program shows how to set/display values for an associative array.*/
|
||||
/*┌────────────────────────────────────────────────────────────────────┐
|
||||
│ The (below) two REXX statements aren't really necessary, but it │
|
||||
│ shows how to define any and all entries in a associative array so │
|
||||
│ that if a "key" is used that isn't defined, it can be displayed to │
|
||||
│ indicate such, or its value can be checked to determine if a │
|
||||
│ particular associative array element has been set (defined). │
|
||||
└────────────────────────────────────────────────────────────────────┘*/
|
||||
stateF.=' [not defined yet] ' /*sets any/all state former caps.*/
|
||||
stateN.=' [not defined yet] ' /*sets any/all state names. */
|
||||
/*┌────────────────────────────────────────────────────────────────────┐
|
||||
│ In REXX, when a "key" is used, it's normally stored (internally) │
|
||||
│ as uppercase characters (as in the examples below). Actually, any │
|
||||
│ characters can be used, including blank(s) and non-displayable │
|
||||
│ characters (including '00'x, 'ff'x, commas, periods, quotes, ···).│
|
||||
└────────────────────────────────────────────────────────────────────┘*/
|
||||
stateL='' /*list of states (empty now). It's nice to be in alpha-*/
|
||||
/*betic order; they'll be listed in this order. With a */
|
||||
/*little more code, they could be sorted quite easily. */
|
||||
/*REXX program demonstrates how to set and display values for an associative array. */
|
||||
/*╔════════════════════════════════════════════════════════════════════════════════════╗
|
||||
║ The (below) two REXX statements aren't really necessary, but it shows how to ║
|
||||
║ define any and all entries in a associative array so that if a "key" is used that ║
|
||||
║ isn't defined, it can be displayed to indicate such, or its value can be checked ║
|
||||
║ to determine if a particular associative array element has been set (defined). ║
|
||||
╚════════════════════════════════════════════════════════════════════════════════════╝*/
|
||||
stateF.= ' [not defined yet] ' /*sets any/all state former capitols.*/
|
||||
stateN.= ' [not defined yet] ' /*sets any/all state names. */
|
||||
w = 0 /*the maximum length of a state name.*/
|
||||
stateL=
|
||||
/*╔════════════════════════════════════════════════════════════════════════════════════╗
|
||||
║ The list of states (empty now). It's convenient to have them in alphabetic order; ║
|
||||
║ they'll be listed in this order. In REXX, when a key is used, it's normally ║
|
||||
║ stored (internally) as as uppercase characters (as in the examples below). ║
|
||||
║ Actually, any characters can be used, including blank(s) and non─displayable ║
|
||||
║ characters (including '00'x, 'ff'x, commas, periods, quotes, ···). ║
|
||||
╚════════════════════════════════════════════════════════════════════════════════════╝*/
|
||||
call setSC 'al', "Alabama" , 'Tuscaloosa'
|
||||
call setSC 'ca', "California" , 'Benicia'
|
||||
call setSC 'co', "Colorado" , 'Denver City'
|
||||
call setSC 'ct', "Connecticut" , 'Hartford and New Haven (jointly)'
|
||||
call setSC 'de', "Delaware" , 'New-Castle'
|
||||
call setSC 'ga', "Georgia" , 'Milledgeville'
|
||||
call setSC 'il', "Illinois" , 'Vandalia'
|
||||
call setSC 'in', "Indiana" , 'Corydon'
|
||||
call setSC 'ia', "Iowa" , 'Iowa City'
|
||||
call setSC 'la', "Louisiana" , 'New Orleans'
|
||||
call setSC 'me', "Maine" , 'Portland'
|
||||
call setSC 'mi', "Michigan" , 'Detroit'
|
||||
call setSC 'ms', "Mississippi" , 'Natchez'
|
||||
call setSC 'mo', "Missouri" , 'Saint Charles'
|
||||
call setSC 'mt', "Montana" , 'Virginia City'
|
||||
call setSC 'ne', "Nebraska" , 'Lancaster'
|
||||
call setSC 'nh', "New Hampshire" , 'Exeter'
|
||||
call setSC 'ny', "New York" , 'New York'
|
||||
call setSC 'nc', "North Carolina" , 'Fayetteville'
|
||||
call setSC 'oh', "Ohio" , 'Chillicothe'
|
||||
call setSC 'ok', "Oklahoma" , 'Guthrie'
|
||||
call setSC 'pa', "Pennsylvania" , 'Lancaster'
|
||||
call setSC 'sc', "South Carolina" , 'Charlestown'
|
||||
call setSC 'tn', "Tennessee" , 'Murfreesboro'
|
||||
call setSC 'vt', "Vermont" , 'Windsor'
|
||||
|
||||
call setSC 'al', "Alabama" ,'Tuscaloosa'
|
||||
call setSC 'ca', "California" ,'Benicia'
|
||||
call setSC 'co', "Colorado" ,'Denver City'
|
||||
call setSC 'ct', "Connecticut" ,'Hartford and New Haven (joint)'
|
||||
call setSC 'de', "Delaware" ,'New-Castle'
|
||||
call setSC 'ga', "Georgia" ,'Milledgeville'
|
||||
call setSC 'il', "Illinois" ,'Vandalia'
|
||||
call setSC 'in', "Indiana" ,'Corydon'
|
||||
call setSC 'ia', "Iowa" ,'Iowa City'
|
||||
call setSC 'la', "Louisiana" ,'New Orleans'
|
||||
call setSC 'me', "Maine" ,'Portland'
|
||||
call setSC 'mi', "Michigan" ,'Detroit'
|
||||
call setSC 'ms', "Mississippi" ,'Natchez'
|
||||
call setSC 'mo', "Missoura" ,'Saint Charles'
|
||||
call setSC 'mt', "Montana" ,'Virginia City'
|
||||
call setSC 'ne', "Nebraska" ,'Lancaster'
|
||||
call setSC 'nh', "New Hampshire" ,'Exeter'
|
||||
call setSC 'ny', "New York" ,'New York'
|
||||
call setSC 'nc', "North Carolina" ,'Fayetteville'
|
||||
call setSC 'oh', "Ohio" ,'Chillicothe'
|
||||
call setSC 'ok', "Oklahoma" ,'Guthrie'
|
||||
call setSC 'pa', "Pennsylvania" ,'Lancaster'
|
||||
call setSC 'sc', "South Carolina" ,'Charlestown'
|
||||
call setSC 'tn', "Tennessee" ,'Murfreesboro'
|
||||
call setSC 'vt', "Vermont" ,'Windsor'
|
||||
|
||||
do j=1 for words(stateL) /*show all capitals that were set*/
|
||||
q=word(stateL,j) /*get the next state in the list.*/
|
||||
say 'the former capital of ('q") " stateN.q " was " stateC.q
|
||||
end /*j*/ /* [↑] display states defined. */
|
||||
exit /*stick a fork in it, we're done.*/
|
||||
/*─────────────────────────────────────setSC subroutine─────────────────*/
|
||||
setSC: arg code; parse arg ,name,cap /*get upper code, get name & cap.*/
|
||||
stateL=stateL code /*keep a list of all state codes.*/
|
||||
stateN.code=name /*set the state's name. */
|
||||
stateC.code=cap /*set the state's capital. */
|
||||
return /*return to invoker, SET is done.*/
|
||||
do j=1 for words(stateL) /*show all capitols that were defined. */
|
||||
q=word(stateL, j) /*get the next (USA) state in the list.*/
|
||||
say 'the former capitol of ('q") " left(stateN.q, w) " was " stateC.q
|
||||
end /*j*/ /* [↑] show states that were defined.*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
setSC: parse arg code,name,cap; upper code /*get code, name & cap.; uppercase code*/
|
||||
stateL=stateL code /*keep a list of all the US state codes*/
|
||||
stateN.code=name; w=max(w,length(name)) /*define the state's name; max width. */
|
||||
stateC.code=cap /* " " " code to the capitol*/
|
||||
return /*return to invoker, SETSC is finished.*/
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
myDict = { "hello" => 13,
|
||||
my_dict = { "hello" => 13,
|
||||
"world" => 31,
|
||||
"!" => 71 }
|
||||
|
||||
# iterating over key-value pairs:
|
||||
myDict.each {|key, value| puts "key = #{key}, value = #{value}"}
|
||||
my_dict.each {|key, value| puts "key = #{key}, value = #{value}"}
|
||||
# or
|
||||
myDict.each_pair {|key, value| puts "key = #{key}, value = #{value}"}
|
||||
my_dict.each_pair {|key, value| puts "key = #{key}, value = #{value}"}
|
||||
|
||||
# iterating over keys:
|
||||
myDict.each_key {|key| puts "key = #{key}"}
|
||||
my_dict.each_key {|key| puts "key = #{key}"}
|
||||
|
||||
# iterating over values:
|
||||
myDict.each_value {|value| puts "value =#{value}"}
|
||||
my_dict.each_value {|value| puts "value =#{value}"}
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
for key, value in myDict
|
||||
for key, value in my_dict
|
||||
puts "key = #{key}, value = #{value}"
|
||||
end
|
||||
|
||||
for key in myDict.keys
|
||||
for key in my_dict.keys
|
||||
puts "key = #{key}"
|
||||
end
|
||||
|
||||
for value in myDict.values
|
||||
for value in my_dict.values
|
||||
puts "value = #{value}"
|
||||
end
|
||||
|
|
|
|||
|
|
@ -1,17 +1,13 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
fn main() {
|
||||
let mut squares = HashMap::new();
|
||||
squares.insert("one", 1);
|
||||
squares.insert("two", 4);
|
||||
squares.insert("three", 9);
|
||||
for key in squares.keys() {
|
||||
println!("Key {}", key);
|
||||
}
|
||||
for value in squares.values() {
|
||||
println!("Value {}", value);
|
||||
}
|
||||
for (key, value) in squares.iter() {
|
||||
println!("{} => {}", key, value);
|
||||
let mut olympic_medals = HashMap::new();
|
||||
olympic_medals.insert("United States", (1072, 859, 749));
|
||||
olympic_medals.insert("Soviet Union", (473, 376, 355));
|
||||
olympic_medals.insert("Great Britain", (246, 276, 284));
|
||||
olympic_medals.insert("Germany", (252, 260, 270));
|
||||
for (country, medals) in olympic_medals {
|
||||
println!("{} has had {} gold medals, {} silver medals, and {} bronze medals",
|
||||
country, medals.0, medals.1, medals.2);
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,25 @@
|
|||
Option Explicit
|
||||
Sub Test()
|
||||
Dim h As Object, i As Long, u, v, s
|
||||
Set h = CreateObject("Scripting.Dictionary")
|
||||
h.Add "A", 1
|
||||
h.Add "B", 2
|
||||
h.Add "C", 3
|
||||
|
||||
'Iterate on keys
|
||||
For Each s In h.Keys
|
||||
Debug.Print s
|
||||
Next
|
||||
|
||||
'Iterate on values
|
||||
For Each s In h.Items
|
||||
Debug.Print s
|
||||
Next
|
||||
|
||||
'Iterate on both keys and values by creating two arrays
|
||||
u = h.Keys
|
||||
v = h.Items
|
||||
For i = 0 To h.Count - 1
|
||||
Debug.Print u(i), v(i)
|
||||
Next
|
||||
End Sub
|
||||
Loading…
Add table
Add a link
Reference in a new issue