Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,6 @@
---
category:
- Iteration
- Data Structures
from: http://rosettacode.org/wiki/Associative_array/Iteration
note: Basic language learning

View file

@ -0,0 +1,8 @@
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>

View file

@ -0,0 +1,10 @@
V d = [key1 = value1, key2 = value2]
L(key, value) d
print(key = value)
L(key) d.keys()
print(key)
L(value) d.values()
print(value)

View file

@ -0,0 +1,3 @@
{"one": 1, "two": "bad"}
( swap . space . cr )
m:each

View file

@ -0,0 +1,3 @@
{"one": 1, "two": "bad"} m:keys
( . cr )
a:each

View file

@ -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

View file

@ -0,0 +1,10 @@
BEGIN {
a["hello"] = 1
a["world"] = 2
a["!"] = 3
# iterate over keys, undefined order
for(key in a) {
print key, a[key]
}
}

View file

@ -0,0 +1,10 @@
BEGIN {
a["hello"] = 1
a["world"] = 2
a["!"] = 3
PROCINFO["sorted_in"] = "@ind_str_asc" # controls index order
# iterate over keys, indices as strings sorted ascending
for(key in a) {
print key, a[key]
}
}

View file

@ -0,0 +1,19 @@
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers.Indefinite_Ordered_Maps;
procedure Test_Iteration is
package String_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (String, Integer);
use String_Maps;
A : Map;
Index : Cursor;
begin
A.Insert ("hello", 1);
A.Insert ("world", 2);
A.Insert ("!", 3);
Index := A.First;
while Index /= No_Element loop
Put_Line (Key (Index) & Integer'Image (Element (Index)));
Index := Next (Index);
end loop;
end Test_Iteration;

View file

@ -0,0 +1,12 @@
record r;
text s;
r_put(r, "A", 33); # an integer value
r_put(r, "C", 2.5); # a real value
r_put(r, "B", "associative"); # a string value
if (r_first(r, s)) {
do {
o_form("key ~, value ~ (~)\n", s, r[s], r_type(r, s));
} while (rsk_greater(r, s, s));
}

View file

@ -0,0 +1,25 @@
; create a dictionary
d: #[
name: "john"
surname: "doe"
age: 34
]
; Iterate over key/value pairs
loop d [key,value][
print ["key =" key ", value =" value]
]
print "----"
; Iterate over keys
loop keys d [k][
print ["key =" k]
]
print "----"
; Iterate over values
loop values d [v][
print ["value =" v]
]

View file

@ -0,0 +1,6 @@
; Create an associative array
obj := Object("red", 0xFF0000, "blue", 0x0000FF, "green", 0x00FF00)
enum := obj._NewEnum()
While enum[key, value]
t .= key "=" value "`n"
MsgBox % t

View file

@ -0,0 +1,26 @@
REM Store some values with their keys:
PROCputdict(mydict$, "FF0000", "red")
PROCputdict(mydict$, "00FF00", "green")
PROCputdict(mydict$, "0000FF", "blue")
REM Iterate through the dictionary:
i% = 1
REPEAT
i% = FNdict(mydict$, i%, v$, k$)
PRINT v$, k$
UNTIL i% = 0
END
DEF PROCputdict(RETURN dict$, value$, key$)
IF dict$ = "" dict$ = CHR$(0)
dict$ += key$ + CHR$(1) + value$ + CHR$(0)
ENDPROC
DEF FNdict(dict$, I%, RETURN value$, RETURN key$)
LOCAL J%, K%
J% = INSTR(dict$, CHR$(1), I%)
K% = INSTR(dict$, CHR$(0), J%)
value$ = MID$(dict$, I%+1, J%-I%-1)
key$ = MID$(dict$, J%+1, K%-J%-1)
IF K% >= LEN(dict$) THEN K% = 0
= K%

View file

@ -0,0 +1,10 @@
DECLARE associative ASSOC STRING
associative("abc") = "first three"
associative("mn") = "middle two"
associative("xyz") = "last three"
LOOKUP associative TO keys$ SIZE amount
FOR i = 0 TO amount - 1
PRINT keys$[i], ":", associative(keys$[i])
NEXT

View file

@ -0,0 +1 @@
births (('Washington' 1732) ('Lincoln' 1809) ('Roosevelt' 1882) ('Kennedy' 1917)) ls2map ! <

View file

@ -0,0 +1 @@
births cp dup {1 +} overmap !

View file

@ -0,0 +1 @@
valmap ! lsnum !

View file

@ -0,0 +1 @@
births ('Roosevelt' 'Kennedy') lumapls ! lsnum !

View file

@ -0,0 +1 @@
births map2ls !

View file

@ -0,0 +1 @@
{give swap << " " << itod << "\n" <<} each

View file

@ -0,0 +1,2 @@
foo (("bar" 17) ("baz" 42)) ls2map ! <
births foo mergemap !

View file

@ -0,0 +1 @@
births map2ls ! {give swap << " " << itod << "\n" <<} each

View file

@ -0,0 +1,18 @@
( new$hash:?myhash
& (myhash..insert)$(title."Some title")
& (myhash..insert)$(formula.a+b+x^7)
& (myhash..insert)$(fruit.apples oranges kiwis)
& (myhash..insert)$(meat.)
& (myhash..insert)$(fruit.melons bananas)
& (myhash..remove)$formula
& (myhash..insert)$(formula.x^2+y^2)
& (myhash..forall)
$ (
= key value
. whl
' ( !arg:(?key.?value) ?arg
& put$("key:" !key "\nvalue:" !value \n)
)
& put$\n
)
);

View file

@ -0,0 +1,16 @@
h = [ hello: 1 world: 2 :! : 3]
#Iterate over key, value pairs
h.each { k, v |
p "Key: #{k} Value: #{v}"
}
#Iterate over keys
h.each_key { k |
p "Key: #{k}"
}
#Iterate over values
h.each_value { v |
p "Value: #{v}"
}

View file

@ -0,0 +1,21 @@
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> dict {
{"One", 1},
{"Two", 2},
{"Three", 7}
};
dict["Three"] = 3;
std::cout << "One: " << dict["One"] << std::endl;
std::cout << "Key/Value pairs: " << std::endl;
for(auto& kv: dict) {
std::cout << " " << kv.first << ": " << kv.second << std::endl;
}
return 0;
}

View file

@ -0,0 +1,12 @@
std::map<std::string, int> myDict;
myDict["hello"] = 1;
myDict["world"] = 2;
myDict["!"] = 3;
// iterating over key-value pairs:
for (std::map<std::string, int>::iterator it = myDict.begin(); it != myDict.end(); ++it) {
// the thing pointed to by the iterator is an std::pair<const std::string, int>&
const std::string& key = it->first;
int& value = it->second;
std::cout << "key = " << key << ", value = " << value << std::endl;
}

View file

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
namespace AssocArrays
{
class Program
{
static void Main(string[] args)
{
Dictionary<string,int> assocArray = new Dictionary<string,int>();
assocArray["Hello"] = 1;
assocArray.Add("World", 2);
assocArray["!"] = 3;
foreach (KeyValuePair<string, int> kvp in assocArray)
{
Console.WriteLine(kvp.Key + " : " + kvp.Value);
}
foreach (string key in assocArray.Keys)
{
Console.WriteLine(key);
}
foreach (int val in assocArray.Values)
{
Console.WriteLine(val.ToString());
}
}
}
}

View file

@ -0,0 +1,21 @@
shared void run() {
value myMap = map {
"foo" -> 5,
"bar" -> 10,
"baz" -> 15
};
for(key in myMap.keys) {
print(key);
}
for(item in myMap.items) {
print(item);
}
for(key->item in myMap) {
print("``key`` maps to ``item``");
}
}

View file

@ -0,0 +1,10 @@
var A = [ "H2O" => "water", "NaCl" => "salt", "O2" => "oxygen" ];
for k in A.domain do
writeln("have key: ", k);
for v in A do
writeln("have value: ", v);
for (k,v) in zip(A.domain, A) do
writeln("have element: ", k, " -> ", v);

View file

@ -0,0 +1,8 @@
(doseq [[k v] {:a 1, :b 2, :c 3}]
(println k "=" v))
(doseq [k (keys {:a 1, :b 2, :c 3})]
(println k))
(doseq [v (vals {:a 1, :b 2, :c 3})]
(println v))

View file

@ -0,0 +1,9 @@
hash =
a: 'one'
b: 'two'
for key, value of hash
console.log key, value
for key of hash
console.log key

View file

@ -0,0 +1,8 @@
;; iterate using dolist, destructure manually
(dolist (pair alist)
(destructuring-bind (key . value) pair
(format t "~&Key: ~a, Value: ~a." key value)))
;; iterate and destructure with loop
(loop for (key . value) in alist
do (format t "~&Key: ~a, Value: ~a." key value))

View file

@ -0,0 +1,2 @@
(loop for (key value) on plist :by 'cddr
do (format t "~&Key: ~a, Value: ~a." key value))

View file

@ -0,0 +1,3 @@
(maphash (lambda (key value)
(format t "~&Key: ~a, Value: ~a." key value))
hash-table)

View file

@ -0,0 +1,2 @@
(loop for key being each hash-key of hash-table using (hash-value value)
do (format t "~&Key: ~a, Value: ~a." key value))

View file

@ -0,0 +1,6 @@
(with-hash-table-iterator (next-entry hash-table)
(loop
(multiple-value-bind (nextp key value) (next-entry)
(if (not nextp)
(return)
(format t "~&Key: ~a, Value: ~a." key value)))))

View file

@ -0,0 +1,11 @@
;; Project : Associative array/Iteration
(setf x (make-array '(3 2)
:initial-contents '(("hello" 13 ) ("world" 31) ("!" 71))))
(setf xlen (array-dimensions x))
(setf len (car xlen))
(dotimes (n len)
(terpri)
(format t "~a" (aref x n 0))
(format t "~a" " : ")
(format t "~a" (aref x n 1)))

View file

@ -0,0 +1,13 @@
dict = {'A' => 1, 'B' => 2}
dict.each { |pair|
puts pair
}
dict.each_key { |key|
puts key
}
dict.each_value { |value|
puts value
}

View file

@ -0,0 +1,40 @@
import std.stdio: writeln;
void main() {
// the associative array
auto aa = ["alice":2, "bob":97, "charlie":45];
// how to iterate key/value pairs:
foreach (key, value; aa)
writeln("1) Got key ", key, " with value ", value);
writeln();
// how to iterate the keys:
foreach (key, _; aa)
writeln("2) Got key ", key);
writeln();
// how to iterate the values:
foreach (value; aa)
writeln("3) Got value ", value);
writeln();
// how to extract the values, lazy:
foreach (value; aa.byValue())
writeln("4) Got value ", value);
writeln();
// how to extract the keys, lazy:
foreach (key; aa.byKey())
writeln("5) Got key ", key);
writeln();
// how to extract all the keys:
foreach (key; aa.keys)
writeln("6) Got key ", key);
writeln();
// how to extract all the values:
foreach (value; aa.values)
writeln("7) Got value ", value);
}

View file

@ -0,0 +1,7 @@
dict = { 'def' => 1, 'abc' => 2 }
for( keyvalue in dict ) io.writeln( keyvalue );
for( key in dict.keys(); value in dict.values() ) io.writeln( key, value )
dict.iterate { [key, value]
io.writeln( key, value )
}

View file

@ -0,0 +1,18 @@
main(){
var fruits = {
'apples': 'red',
'oranges': 'orange',
'bananas': 'yellow',
'pears': 'green',
'plums': 'purple'
};
print('Key Value pairs:');
fruits.forEach( (fruits, color) => print( '$fruits are $color' ) );
print('\nKeys only:');
fruits.keys.forEach( ( key ) => print( key ) );
print('\nValues only:');
fruits.values.forEach( ( value ) => print( value ) );
}

View file

@ -0,0 +1,29 @@
program AssociativeArrayIteration;
{$APPTYPE CONSOLE}
uses SysUtils, Generics.Collections;
var
i: Integer;
s: string;
lDictionary: TDictionary<string, Integer>;
lPair: TPair<string, Integer>;
begin
lDictionary := TDictionary<string, Integer>.Create;
try
lDictionary.Add('foo', 5);
lDictionary.Add('bar', 10);
lDictionary.Add('baz', 15);
lDictionary.AddOrSetValue('foo', 6);
for lPair in lDictionary do
Writeln(Format('Pair: %s = %d', [lPair.Key, lPair.Value]));
for s in lDictionary.Keys do
Writeln('Key: ' + s);
for i in lDictionary.Values do
Writeln('Value: ', i);
finally
lDictionary.Free;
end;
end.

View file

@ -0,0 +1,5 @@
var t = (x: 1, y: 2, z: 3)
for x in t.Keys() {
print("\(x)=\(t[x])")
}

View file

@ -0,0 +1,21 @@
def map := [
"a" => 1,
"b" => 2,
"c" => 3,
]
for key => value in map {
println(`$key $value`)
}
for value in map { # ignore keys
println(`. $value`)
}
for key => _ in map { # ignore values
println(`$key .`)
}
for key in map.domain() { # iterate over the set whose values are the keys
println(`$key .`)
}

View file

@ -0,0 +1,15 @@
Map map = text%text["Italy" => "Rome", "France" => "Paris"]
map.insert("Germany", "Berlin")
map["Spain"] = "Madrid"
writeLine("== pairs ==")
for each Pair pair in map
writeLine(pair)
end
writeLine("== keys ==")
for each text key in map.keys()
writeLine(key)
end
writeLine("== values ==")
for each text value in map.values()
writeLine(value)
end

View file

@ -0,0 +1,13 @@
associative$[][] = [ [ 1 "associative" ] [ 2 "arrays" ] ]
print "Key-value pairs:"
for i = 1 to len associative$[][]
print associative$[i][1] & " " & associative$[i][2]
.
print "Just keys:"
for i = 1 to len associative$[][]
print associative$[i][1]
.
print "Just values:"
for i = 1 to len associative$[][]
print associative$[i][2]
.

View file

@ -0,0 +1,24 @@
(lib 'hash) ;; load hash.lib
(define H (make-hash))
;; fill hash table
(hash-set H 'Simon 42)
(hash-set H 'Albert 666)
(hash-set H 'Antoinette 33)
;; iterate over (key . value ) pairs
(for ([kv H]) (writeln kv))
(Simon . 42)
(Albert . 666)
(Antoinette . 33)
;; iterate over keys
(for ([k (hash-keys H)]) (writeln 'key-> k))
key-> Simon
key-> Albert
key-> Antoinette
;; iterate over values
(for ([v (hash-values H)]) (writeln 'value-> v))
value-> 42
value-> 666
value-> 33

View file

@ -0,0 +1,18 @@
import system'collections;
import system'routines;
import extensions;
public program()
{
// 1. Create
var map := Dictionary.new();
map["key"] := "foox";
map["key"] := "foo";
map["key2"]:= "foo2";
map["key3"]:= "foo3";
map["key4"]:= "foo4";
// Enumerate
map.forEach:
(keyValue){ console.printLine(keyValue.Key," : ",keyValue.Value) }
}

View file

@ -0,0 +1,18 @@
import system'collections;
import system'routines;
import extensions;
public program()
{
// 1. Create
auto map := new Map<string,string>();
map["key"] := "foox";
map["key"] := "foo";
map["key2"]:= "foo2";
map["key3"]:= "foo3";
map["key4"]:= "foo4";
// Enumerate
map.forEach:
(tuple){ console.printLine(tuple.Item1," : ",tuple.Item2) }
}

View file

@ -0,0 +1,5 @@
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)

View file

@ -0,0 +1,13 @@
-module(assoc).
-compile([export_all]).
test_create() ->
D = dict:new(),
D1 = dict:store(foo,1,D),
D2 = dict:store(bar,2,D1),
print_vals(D2).
print_vals(D) ->
lists:foreach(fun (K) ->
io:format("~p: ~b~n",[K,dict:fetch(K,D)])
end, dict:fetch_keys(D)).

View file

@ -0,0 +1,4 @@
let myMap = [ ("Hello", 1); ("World", 2); ("!", 3) ]
for k, v in myMap do
printfn "%s -> %d" k v

View file

@ -0,0 +1,7 @@
// Only prints the keys.
for k, _ in myMap do
printfn "%s" k
// Only prints the values.
for _, v in myMap do
printfn "%d" v

View file

@ -0,0 +1 @@
H{ { "hi" "there" } { "a" "b" } } [ ": " glue print ] assoc-each

View file

@ -0,0 +1,2 @@
H{ { "hi" "there" } { "a" "b" } } [ drop print ] assoc-each ! print keys
H{ { "hi" "there" } { "a" "b" } } [ nip print ] assoc-each ! print values

View file

@ -0,0 +1,22 @@
class Main
{
public static Void main ()
{
Int:Str map := [1:"alpha", 2:"beta", 3:"gamma"]
map.keys.each |Int key|
{
echo ("Key is: $key")
}
map.vals.each |Str value|
{
echo ("Value is: $value")
}
map.each |Str value, Int key|
{
echo ("Key $key maps to $value")
}
}
}

View file

@ -0,0 +1,22 @@
include ffl/hct.fs
include ffl/hci.fs
\ Create hashtable and iterator in dictionary
10 hct-create htable
htable hci-create hiter
\ Insert entries
1 s" hello" htable hct-insert
2 s" world" htable hct-insert
3 s" !" htable hct-insert
: iterate
hiter hci-first
BEGIN
WHILE
." key = " hiter hci-key type ." , value = " . cr
hiter hci-next
REPEAT
;
iterate

View file

@ -0,0 +1,137 @@
\ Written in ANS-Forth; tested under VFX.
\ Requires the novice package: http://www.forth.org/novice.html
\ The following should already be done:
\ include novice.4th
\ include association.4th
\ I would define high-level languages as those that allow programs to be written without explicit iteration. Iteration is a major source of bugs.
\ The example from the FFL library doesn't hide iteration, whereas this example from the novice-package does.
marker AssociationIteration.4th
\ ******
\ ****** The following defines a node in an association (each node is derived from ELEMENT).
\ ******
element
w field .inventor
constant language \ describes a programming language
: init-language ( inventor name node -- node )
init-element >r
hstr r@ .inventor !
r> ;
: new-language ( inventor name -- node )
language alloc
init-language ;
: show-language ( count node -- )
>r
1+ \ -- count+1
cr r@ .key @ count colorless type ." invented by: " r@ .inventor @ count type
rdrop ;
: show-languages-forward ( handle -- )
0 \ -- handle count
swap .root @ ['] show-language walk>
cr ." count: " .
cr ;
: show-languages-backward ( handle -- )
0 \ -- handle count
swap .root @ ['] show-language <walk
cr ." count: " .
cr ;
: kill-language-attachments ( node -- )
dup .inventor @ dealloc
kill-key ;
: copy-language-attachments ( src dst -- )
over .inventor @ hstr
over .inventor !
copy-key ;
\ ******
\ ****** The following defines the association itself (the handle).
\ ******
association
constant languages \ describes a set of programming languages
: init-languages ( record -- record )
>r
['] compare ['] kill-language-attachments ['] copy-language-attachments
r> init-association ;
: new-languages ( -- record )
languages alloc
init-languages ;
\ ******
\ ****** The following filters one association into another, including everything that matches a particular inventor.
\ ******
: <filter-inventor> { inventor handle new-handle node -- inventor handle new-handle }
inventor count node .inventor @ count compare A=B = if
node handle dup-element new-handle insert then
inventor handle new-handle ;
: filter-inventor ( inventor handle -- new-handle )
dup similar-association \ -- inventor handle new-handle
over .root @ ['] <filter-inventor> walk> \ -- inventor handle new-handle
nip nip ;
\ ******
\ ****** The following is a demonstration with some sample data.
\ ******
new-languages
c" Moore, Chuck" c" Forth " new-language over insert
c" Ichiah, Jean" c" Ada " new-language over insert
c" Wirth, Niklaus" c" Pascal " new-language over insert
c" Wirth, Niklaus" c" Oberon " new-language over insert
c" McCarthy, John" c" Lisp " new-language over insert
c" van Rossum, Guido" c" Python " new-language over insert
c" Gosling, Jim" c" Java " new-language over insert
c" Ierusalimschy, Roberto" c" Lua " new-language over insert
c" Matsumoto, Yukihiro" c" Ruby " new-language over insert
c" Pestov, Slava" c" Factor " new-language over insert
c" Gosling, James" c" Java " new-language over insert
c" Wirth, Niklaus" c" Modula-2 " new-language over insert
c" Ritchie, Dennis" c" C " new-language over insert
c" Stroustrup, Bjarne" c" C++ " new-language over insert
constant some-languages
cr .( everything in SOME-LANGUAGES ordered forward: )
some-languages show-languages-forward
cr .( everything in SOME-LANGUAGES ordered backward: )
some-languages show-languages-backward
cr .( everything in SOME-LANGUAGES invented by Wirth: )
c" Wirth, Niklaus" some-languages filter-inventor dup show-languages-forward kill-association
cr .( everything in SOME-LANGUAGES within 'F' and 'L': )
c" F" c" L" some-languages filter within dup show-languages-forward kill-association
cr .( everything in SOME-LANGUAGES not within 'F' and 'L': )
c" F" c" L" some-languages filter without dup show-languages-forward kill-association
some-languages kill-association

View file

@ -0,0 +1,30 @@
program AssociativeArrayIteration;
{$mode delphi}{$ifdef windows}{$apptype console}{$endif}
uses Generics.Collections;
type
TlDictionary = TDictionary<string, Integer>;
TlPair = TPair<string,integer>;
var
i: Integer;
s: string;
lDictionary: TlDictionary;
lPair: TlPair;
begin
lDictionary := TlDictionary.Create;
try
lDictionary.Add('foo', 5);
lDictionary.Add('bar', 10);
lDictionary.Add('baz', 15);
lDictionary.AddOrSetValue('foo',6);
for lPair in lDictionary do
Writeln('Pair: ',Lpair.Key,' = ',lPair.Value);
for s in lDictionary.Keys do
Writeln('Key: ' + s);
for i in lDictionary.Values do
Writeln('Value: ', i);
finally
lDictionary.Free;
end;
end.

View file

@ -0,0 +1,27 @@
#include"assoc.bas"
function get_dict_data_string( d as dicitem ) as string
select case d.datatype
case BOOL
if d.value.bool then return "true" else return "false"
case INTEG
return str(d.value.integ)
case STRNG
return """"+d.value.strng+""""
case FLOAT
return str(d.value.float)
case BYYTE
return str(d.value.byyte)
case else
return "DATATYPE ERROR"
end select
end function
sub print_keyval_pair( d as dicentry )
print using "{&} : {&}";get_dict_data_string( d.key ); get_dict_data_string(d.value)
end sub
for i as uinteger = 0 to ubound(Dictionary)
print_keyval_pair(Dictionary(i))
next i

View file

@ -0,0 +1,7 @@
d = new dict[[[1, "one"], [2, "two"]]]
for [key, value] = d
println["$key\t$value"]
println[]
for key = keys[d]
println["$key"]

View file

@ -0,0 +1,12 @@
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
CFStringRef key
for key in dict
print key, dict[key]
next
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,12 @@
void local fn MyDictEnumerator( dict as CFDictionaryRef, key as CFTypeRef, obj as CFTypeRef, stp as ^BOOL, userData as ptr )
print key, obj
end fn
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
DictionaryEnumerateKeysAndObjects( dict, @fn MyDictEnumerator, NULL )
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,13 @@
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
CFArrayRef keys = fn DictionaryAllKeys( dict )
CFStringRef key
for key in keys
print key, dict[key]
next
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,13 @@
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
CFArrayRef values = fn DictionaryAllValues( dict )
CFStringRef value
for value in values
print value
next
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,25 @@
void local fn DoIt
CFDictionaryRef dict = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
CFStringRef key
CFTypeRef obj
EnumeratorRef keyEnumerator = fn DictionaryKeyEnumerator( dict )
key = fn EnumeratorNextObject( keyEnumerator )
while ( key )
print key,dict[key]
key = fn EnumeratorNextObject( keyEnumerator )
wend
print
EnumeratorRef objectEnumerator = fn DictionaryObjectEnumerator( dict )
obj = fn EnumeratorNextObject( objectEnumerator )
while ( obj )
print obj
obj = fn EnumeratorNextObject( objectEnumerator )
wend
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,16 @@
Public Sub Main()
Dim cList As Collection = ["2": "quick", "4": "fox", "1": "The", "9": "dog", "7": "the", "5": "jumped", "3": "brown", "6": "over", "8": "lazy"]
Dim siCount As Short
Dim sTemp As String
For Each sTemp In cList
Print cList.key & "=" & sTemp;;
Next
Print
For siCount = 1 To cList.Count
Print cList[Str(siCount)];;
Next
End

View file

@ -0,0 +1,19 @@
myMap := map[string]int {
"hello": 13,
"world": 31,
"!" : 71 }
// iterating over key-value pairs:
for key, value := range myMap {
fmt.Printf("key = %s, value = %d\n", key, value)
}
// iterating over keys:
for key := range myMap {
fmt.Printf("key = %s\n", key)
}
// iterating over values:
for _, value := range myMap {
fmt.Printf("value = %d\n", value)
}

View file

@ -0,0 +1,35 @@
package main
import (
"os"
"text/template"
)
func main() {
m := map[string]int{
"hello": 13,
"world": 31,
"!": 71,
}
// iterating over key-value pairs:
template.Must(template.New("").Parse(`
{{- range $k, $v := . -}}
key = {{$k}}, value = {{$v}}
{{end -}}
`)).Execute(os.Stdout, m)
// iterating over keys:
template.Must(template.New("").Parse(`
{{- range $k, $v := . -}}
key = {{$k}}
{{end -}}
`)).Execute(os.Stdout, m)
// iterating over values:
template.Must(template.New("").Parse(`
{{- range . -}}
value = {{.}}
{{end -}}
`)).Execute(os.Stdout, m)
}

View file

@ -0,0 +1,12 @@
def map = [lastName: "Anderson", firstName: "Thomas", nickname: "Neo", age: 24, address: "everywhere"]
println "Entries:"
map.each { println it }
println()
println "Keys:"
map.keySet().each { println it }
println()
println "Values:"
map.values().each { println it }

View file

@ -0,0 +1,11 @@
LOCAL arr := { 6 => 16, "eight" => 8, "eleven" => 11 }
LOCAL x
FOR EACH x IN arr
// key, value
? x:__enumKey(), x
// or key only
? x:__enumKey()
// or value only
? x
NEXT

View file

@ -0,0 +1,13 @@
import qualified Data.Map as M
myMap :: M.Map String Int
myMap = M.fromList [("hello", 13), ("world", 31), ("!", 71)]
main :: IO ()
main =
(putStrLn . unlines) $
[ show . M.toList -- Pairs
, show . M.keys -- Keys
, show . M.elems -- Values
] <*>
pure myMap

View file

@ -0,0 +1,15 @@
procedure main()
t := table()
every t[a := !"ABCDE"] := map(a)
every pair := !sort(t) do
write("\t",pair[1]," -> ",pair[2])
writes("Keys:")
every writes(" ",key(t))
write()
writes("Values:")
every writes(" ",!t)
write()
end

View file

@ -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)
)

View file

@ -0,0 +1 @@
nl__example 0

View file

@ -0,0 +1 @@
get__example each nl__example 0

View file

@ -0,0 +1 @@
(,&< get__example) each nl__example 0

View file

@ -0,0 +1,13 @@
fn main() {
let dictionary = ["foo": 1, "bar": 2]
for entry in dictionary {
// To get values, use
// let value = entry.1
println("{}", entry)
}
// Just keys
for key in dictionary.keys() {
println("{}", key)
}
}

View file

@ -0,0 +1,2 @@
for (Map.Entry<String, Integer> entry : map.entrySet())
System.out.println(entry);

View file

@ -0,0 +1,2 @@
for (String key : map.keySet())
System.out.println(key);

View file

@ -0,0 +1,2 @@
for (int value : map.values())
System.out.println(value);

View file

@ -0,0 +1,15 @@
Map<String, Integer> map = new HashMap<>();
map.put("hello", 1);
map.put("world", 2);
map.put("!", 3);
// iterating over key-value pairs:
map.forEach((k, v) -> {
System.out.printf("key = %s, value = %s%n", k, v);
});
// iterating over keys:
map.keySet().forEach(k -> System.out.printf("key = %s%n", k));
// iterating over values:
map.values().forEach(v -> System.out.printf("value = %s%n", v));

View file

@ -0,0 +1,18 @@
var myhash = {}; //a new, empty object
myhash["hello"] = 3;
myhash.world = 6; //obj.name is equivalent to obj["name"] for certain values of name
myhash["!"] = 9;
//iterate using for..in loop
for (var key in myhash) {
//ensure key is in object and not in prototype
if (myhash.hasOwnProperty(key)) {
console.log("Key is: " + key + '. Value is: ' + myhash[key]);
}
}
//iterate using ES5.1 Object.keys() and Array.prototype.Map()
var keys = Object.keys(); //get Array of object keys (doesn't get prototype keys)
keys.map(function (key) {
console.log("Key is: " + key + '. Value is: ' + myhash[key]);
});

View file

@ -0,0 +1,31 @@
def mydict: {"hello":13, "world": 31, "!": 71};
# Iterating over the keys
mydict | keys[]
# "!"
# "hello"
# "world"
# Iterating over the values:
mydict[]
# 13
# 31
# 71
# Generating a stream of {"key": key, "value": value} objects:
mydict | to_entries[]
# {"key":"hello","value":13}
# {"key":"world","value":31}
# {"key":"!","value":71}
# Generating a stream of [key,value] arrays:
mydict | . as $o | keys[] | [., $o[.]]
#["!",71]
#["hello",13]
#["world",31]
# Generating a stream of [key,value] arrays, without sorting (jq > 1.4 required)
mydict | . as $o | keys_unsorted[] | [., $o[.]]
# ["hello",13]
# ["world",31]
# ["!",71]

View file

@ -0,0 +1,19 @@
dict = Dict("hello" => 13, "world" => 31, "!" => 71)
# applying a function to key-value pairs:
foreach(println, dict)
# iterating over key-value pairs:
for (key, value) in dict
println("dict[$key] = $value")
end
# iterating over keys:
for key in keys(dict)
@show key
end
# iterating over values:
for value in values(dict)
@show value
end

View file

@ -0,0 +1 @@
d: .((`"hello";1); (`"world";2);(`"!";3))

View file

@ -0,0 +1,7 @@
!d
`hello `world `"!"
$!d / convert keys (symbols) as strings
("hello"
"world"
,"!")

View file

@ -0,0 +1,4 @@
`0:{,/$x,": ",d[x]}'!d
hello: 1
world: 2
!: 3

View file

@ -0,0 +1,5 @@
d[]
1 2 3
{x+1}'d[]
2 3 4

View file

@ -0,0 +1,9 @@
fun main(a: Array<String>) {
val map = mapOf("hello" to 1, "world" to 2, "!" to 3)
with(map) {
entries.forEach { println("key = ${it.key}, value = ${it.value}") }
keys.forEach { println("key = $it") }
values.forEach { println("value = $it") }
}
}

View file

@ -0,0 +1,7 @@
(let ((data '(#(key1 "foo") #(key2 "bar")))
(hash (: dict from_list data)))
(: dict fold
(lambda (key val accum)
(: io format '"~s: ~s~n" (list key val)))
0
hash))

View file

@ -0,0 +1,6 @@
(let ((data '(#(key1 "foo") #(key2 "bar")))
(hash (: dict from_list data)))
(: lists map
(lambda (key)
(: io format '"~s~n" (list key)))
(: dict fetch_keys hash)))

View file

@ -0,0 +1,4 @@
: first 0 extract nip ; : second 1 extract nip ; : nip swap drop ;
: say(*) dup first " => " 2 compress "" join . second . ;
[['foo 5] ['bar 10] ['baz 20]] 'say apply drop

View file

@ -0,0 +1,29 @@
//iterate over associative array
//Lasso maps
local('aMap' = map('weight' = 112,
'height' = 45,
'name' = 'jason'))
' Map output: \n '
#aMap->forEachPair => {^
//display pair, then show accessing key and value individually
#1+'\n '
#1->first+': '+#1->second+'\n '
^}
//display keys and values separately
'\n'
' Map Keys: '+#aMap->keys->join(',')+'\n'
' Map values: '+#aMap->values->join(',')+'\n'
//display using forEach
'\n'
' Use ForEach to iterate Map keys: \n'
#aMap->keys->forEach => {^
#1+'\n'
^}
'\n'
' Use ForEach to iterate Map values: \n'
#aMap->values->forEach => {^
#1+'\n'
^}
//the {^ ^} indicates that output should be printed (AutoCollect) ,
// if output is not desired, just { } is used

View file

@ -0,0 +1,23 @@
data "red", "255 50 50", "green", "50 255 50", "blue", "50 50 255"
data "my fave", "220 120 120", "black", "0 0 0"
myAssocList$ =""
for i =1 to 5
read k$
read dat$
call sl.Set myAssocList$, k$, dat$
next i
keys$ = "" ' List to hold the keys in myList$.
keys = 0
keys = sl.Keys( myAssocList$, keys$)
print " Number of key-data pairs ="; keys
For i = 1 To keys
keyName$ = sl.Get$( keys$, Str$( i))
Print " Key "; i; ":", keyName$, "Data: ", sl.Get$( myAssocList$, keyName$)
Next i
end

View file

@ -0,0 +1,11 @@
hash = [#key1:"value1", #key2:"value2", #key3:"value3"]
-- iterate over key-value pairs
repeat with i = 1 to hash.count
put hash.getPropAt(i) & "=" & hash[i]
end repeat
-- iterating over values only can be written shorter
repeat with val in hash
put val
end repeat

View file

@ -0,0 +1,24 @@
put 3 into fruit["apples"]
put 5 into fruit["pears"]
put 6 into fruit["oranges"]
put "none" into fruit["bananas"]
put "Keys:" & cr & the keys of fruit & cr into tTmp
put "Values 1:" & tab after tTmp
repeat for each line tKey in the keys of fruit
put fruit[tkey] & comma after tTmp
end repeat
-- need to copy array as combine will change variable
put fruit into fruit2
combine fruit2 using comma
put cr & "Values2:" & tab after tTmp
repeat for each item f2val in fruit2
put f2val & comma after tTmp
end repeat
combine fruit using return and ":"
put cr & "Key:Values" & cr & fruit after tTmp
-- alternatively, use same loop as for values 1 with tkey && fruit[tKey]
put tTmp

View file

@ -0,0 +1,12 @@
Keys:
apples
pears
oranges
bananas
Values 1: 3,5,6,none,
Values2: 3,none,6,5,
Key:Values
apples:3
bananas:none
oranges:6
pears:5

View file

@ -0,0 +1,9 @@
local t = {
["foo"] = "bar",
["baz"] = 6,
fortytwo = 7
}
for key,val in pairs(t) do
print(string.format("%s: %s", key, val))
end

View file

@ -0,0 +1,57 @@
Module checkit {
\\ Inventories are objects with keys and values, or keys (used as read only values)
\\ They use hash function.
\\ Function TwoKeys return Inventory object (as a pointer to object)
Function TwoKeys {
Inventory Alfa="key1":=100, "key2":=200
=Alfa
}
M=TwoKeys()
Print Type$(M)="Inventory"
\\ Normal Use:
\\ Inventories Keys are case sensitive
\\ M2000 identifiers are not case sensitive
Print M("key1"), m("key2")
\\ numeric values can convert to strings
Print M$("key1"), m$("key2")
\\ Iteration
N=Each(M)
While N {
Print Eval(N) ' prints 100, 200 as number
Print M(N^!) ' The same using index N^
}
N=Each(M)
While N {
Print Eval$(N) ' prints 100, 200 as strings
Print M$(N^!) ' The same using index N^
}
N=Each(M)
While N {
Print Eval$(N, N^) ' Prints Keys
}
\\ double iteration
Append M, "key3":=500
N=Each(M, 1, -1) ' start to end
N1=Each(M, -1, 1) ' end to start
\\ 3x3 prints
While N {
While N1 {
Print format$("{0}*{1}={2}", Eval(N1), Eval(N), Eval(N1)*Eval(N))
}
}
\\ sort results from lower product to greater product (3+2+1, 6 prints only)
N=Each(M, 1, -1)
While N {
N1=Each(M, N^+1, -1)
While N1 {
Print format$("{0}*{1}={2}", Eval(N1), Eval(N), Eval(N1)*Eval(N))
}
}
N=Each(M)
N1=Each(M,-2, 1) ' from second from end to start
\\ print only 2 values. While block ends when one iterator finish
While N, N1 {
Print Eval(N1)*Eval(N)
}
}
Checkit

Some files were not shown because too many files have changed in this diff Show more