Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1,3 +1,6 @@
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}}

View file

@ -7,6 +7,6 @@ r_put(r, "B", "associative"); # a string value
if (r_first(r, s)) {
do {
o_plan("key ", s, ", value ", r_query(r, s), " (", r_type(r, s), ")\n");
o_form("key ~, value ~ (~)\n", s, r[s], r_type(r, s));
} while (r_greater(r, s, s));
}

View file

@ -0,0 +1,21 @@
((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 }))

View file

@ -1,12 +1,9 @@
#include <map>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
int main() {
using MyDict = std::map<std::string, int>;
MyDict dict = {
std::map<std::string, int> dict {
{"One", 1},
{"Two", 2},
{"Three", 7}
@ -15,15 +12,6 @@ int main() {
dict["Three"] = 3;
std::cout << "One: " << dict["One"] << std::endl;
// Make vector of the keys from our map
std::vector<std::string> keys;
std::transform(dict.begin(), dict.end(), std::back_inserter(keys),
[](MyDict::value_type& kv) { return kv.first; });
std::cout << "Keys: " << std::endl;
for(auto& key: keys) std::cout << " " << key << std::endl;
std::cout << "Key/Value pairs: " << std::endl;
for(auto& kv: dict) {
std::cout << " " << kv.first << ": " << kv.second << std::endl;

View file

@ -4,9 +4,9 @@ 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 a pair<std::string, int>
std::string key = it->first;
int value = it->second;
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

@ -1,3 +1,7 @@
m = { 'def' => 1, 'abc' => 2 }
for( kv in m ) io.writeln( kv );
for( k in m.keys(); v in m.values() ) io.writeln( k, v )
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,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,15 @@
Map<String, Integer> myDict = new HashMap<>();
myDict.put("hello", 1);
myDict.put("world", 2);
myDict.put("!", 3);
// iterating over key-value pairs:
myDict.forEach((k, v) -> {
System.out.printf("key = %s, value = %s%n", k, v);
});
// iterating over keys:
myDict.keySet().forEach(k -> System.out.printf("key = %s%n", k));
// iterating over values:
myDict.values().forEach(v -> System.out.printf("value = %s%n", v));

View file

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

View file

@ -0,0 +1,9 @@
> T := table( [ "A" = 1, "B" = 2, "C" = 3, "D" = 4 ] );
> for i in indices( T, nolist ) do print(i ) end:
"A"
"B"
"C"
"D"

View file

@ -0,0 +1,7 @@
> T := table( [ "a" = 1, "b" = 2, ("c","d") = 3 ] ):
> for i in indices( T ) do print( i, T[ op( i ) ] ) end:
["a"], 1
["b"], 2
["c", "d"], 3

View file

@ -0,0 +1,6 @@
> for i in indices( T, pairs ) do print( i) end:
"a" = 1
"b" = 2
("c", "d") = 3

View file

@ -0,0 +1,6 @@
> for i in entries( T ) do print( i) end:
[1]
[3]
[2]

View file

@ -1,21 +0,0 @@
> T := table( [ "a" = 1, "b" = 2, ("c","d") = 3 ] ):
> for i in indices( T ) do print( i, T[ op( i ) ] ) end:
["a"], 1
["c", "d"], 3
["b"], 2
> for i in indices( T ) do print( op( i ) ) end:
"a"
"c", "d"
"b"
> for i in entries( T ) do print( i) end:
[1]
[3]
[2]

View file

@ -0,0 +1,12 @@
;; using an association list:
(setq alist '(("A" "a") ("B" "b") ("C" "c")))
;; list keys
(map first alist)
;; list values
(map last alist)
;; loop over the assocation list:
(dolist (elem alist)
(println (format "%s -> %s" (first elem) (last elem))))

View file

@ -0,0 +1,41 @@
MODULE AssociativeArray;
IMPORT
ADT:Dictionary,
Object:Boxed,
Out;
TYPE
Key = STRING;
Value = Boxed.LongInt;
VAR
assocArray: Dictionary.Dictionary(Key,Value);
iterK: Dictionary.IterKeys(Key,Value);
iterV: Dictionary.IterValues(Key,Value);
aux: Value;
k: Key;
BEGIN
assocArray := NEW(Dictionary.Dictionary(Key,Value));
assocArray.Set("ten",NEW(Value,10));
assocArray.Set("eleven",NEW(Value,11));
aux := assocArray.Get("ten");
Out.LongInt(aux.value,0);Out.Ln;
aux := assocArray.Get("eleven");
Out.LongInt(aux.value,0);Out.Ln;Out.Ln;
(* Iterate keys *)
iterK := assocArray.IterKeys();
WHILE (iterK.Next(k)) DO
Out.Object(k);Out.Ln
END;
Out.Ln;
(* Iterate values *)
iterV := assocArray.IterValues();
WHILE (iterV.Next(aux)) DO
Out.LongInt(aux.value,0);Out.Ln
END
END AssociativeArray.

View file

@ -1,10 +1,10 @@
/*REXX program shows how to set/display values for an associative array.*/
/*┌────────────────────────────────────────────────────────────────────┐
The (below) two REXX statements aren't really necessary, but it
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 it has
been set.
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. */
@ -12,13 +12,11 @@ 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, ...).
characters (including '00'x, 'ff'x, commas, periods, quotes, ···).
*/
stateL='' /*list of states (empty now). */
/*nice to be in alphabetic order,*/
/*they'll be listed in this order*/
/*With a little more code, they */
/* could be sorted quite easily.*/
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. */
call setSC 'al', "Alabama" ,'Tuscaloosa'
call setSC 'ca', "California" ,'Benicia'
@ -46,14 +44,14 @@ call setSC 'sc', "South Carolina" ,'Charlestown'
call setSC 'tn', "Tennessee" ,'Murfreesboro'
call setSC 'vt', "Vermont" ,'Windsor'
do j=1 for words(stateL) /*list all capitals that were set*/
q=word(stateL,j)
say 'the former capital of ('q")" stateN.q "was" stateC.q
end /*j*/
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 /*return to invoker, SET is done.*/

View file

@ -0,0 +1,11 @@
for key, value in myDict
puts "key = #{key}, value = #{value}"
end
for key in myDict.keys
puts "key = #{key}"
end
for value in myDict.values
puts "value = #{value}"
end

View file

@ -0,0 +1,16 @@
use std::collections::HashMap;
fn main() {
let mut squares = HashMap::new();
squares.insert("one", 1i32);
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);
}
}

View file

@ -1,7 +1,7 @@
val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands")
val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands")
println(f"Key->Value: ${m.mkString(", ")}%s")
println(f"Pairs: ${m.toList.mkString(", ")}%s")
println(f"Keys: ${m.keys.mkString(", ")}%s")
println(f"Values: ${m.values.mkString(", ")}%s")
println(f"Unique values: ${m.values.toSet.mkString(", ")}%s")
println(f"Key->Value: ${m.mkString(", ")}%s")
println(f"Pairs: ${m.toList.mkString(", ")}%s")
println(f"Keys: ${m.keys.mkString(", ")}%s")
println(f"Values: ${m.values.mkString(", ")}%s")
println(f"Unique values: ${m.values.toSet.mkString(", ")}%s")

View file

@ -0,0 +1,11 @@
;; Create an associative array (hash-table) whose keys are strings:
(define table (hash-table 'string=?
'("hello" . 0) '("world" . 22) '("!" . 999)))
;; Iterate over the table, passing the key and the value of each entry
;; as arguments to a function:
(hash-table-for-each
table
;; Create by "partial application" a function that accepts 2 arguments,
;; the key and the value:
(pa$ format #t "Key = ~a, Value = ~a\n"))

View file

@ -0,0 +1,11 @@
;; Iterate over the table and create a list of the keys and the
;; altered values:
(hash-table-map
table
(lambda (key val) (list key (+ val 5000))))
;; Create a new table that has the same keys but altered values.
(use gauche.collection)
(map-to <hash-table>
(lambda (k-v) (cons (car k-v) (+ (cdr k-v) 5000)))
table)

View file

@ -1,4 +1,4 @@
a=([key1]=value1 [key2]=value2)
typeset -A a=([key1]=value1 [key2]=value2)
# just keys
printf '%s\n' "${!a[@]}"

View file

@ -0,0 +1,18 @@
let dict = {"apples": 11, "oranges": 25, "pears": 4}
echo "Iterating over key-value pairs"
for [key, value] in items(dict)
echo key " => " value
endfor
echo "\n"
echo "Iterating over keys"
for key in keys(dict)
echo key
endfor
echo "\n"
echo "Iterating over values"
for value in values(dict)
echo value
endfor