Add all the A tasks

This commit is contained in:
Ingy döt Net 2013-04-10 14:58:50 -07:00
parent 2dd7375f96
commit 051504d65b
1608 changed files with 18584 additions and 0 deletions

View file

@ -0,0 +1,3 @@
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.
* Related task: [[Associative arrays/Creation]]

View file

@ -0,0 +1,5 @@
---
category:
- Iteration
- Data Structures
note: Basic language learning

View file

@ -0,0 +1,10 @@
BEGIN {
a["hello"] = 1
a["world"] = 2
a["!"] = 3
# iterate over keys
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,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,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,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,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,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,10 @@
import qualified Data.Map as M
myMap = M.fromList [("hello", 13), ("world", 31), ("!", 71)]
main = do -- pairs
print $ M.toList myMap
-- keys
print $ M.keys myMap
-- values
print $ M.elems myMap

View file

@ -0,0 +1,21 @@
Map<String, Integer> myDict = new HashMap<String, Integer>();
myDict.put("hello", 1);
myDict.put("world", 2);
myDict.put("!", 3);
// iterating over key-value pairs:
for (Map.Entry<String, Integer> e : myDict.entrySet()) {
String key = e.getKey();
Integer value = e.getValue();
System.out.println("key = " + key + ", value = " + value);
}
// iterating over keys:
for (String key : myDict.keySet()) {
System.out.println("key = " + key);
}
// iterating over values:
for (Integer value : myDict.values()) {
System.out.println("value = " + value);
}

View file

@ -0,0 +1,15 @@
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;
var output = '', // initialise as string
key;
for (key in myhash) {
if (myhash.hasOwnProperty(key)) {
output += "key is: " + key;
output += " => ";
output += "value is: " + myhash[key]; // cannot use myhash.key, that would be myhash["key"]
output += "\n";
}
}

View file

@ -0,0 +1,13 @@
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;
var output = '', // initialise as string
val;
for (val in myhash) {
if (myhash.hasOwnProperty(val)) {
output += "myhash['" + val + "'] is: " + myhash[val];
output += "\n";
}
}

View file

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

View file

@ -0,0 +1,20 @@
<?php
$pairs = array( "hello" => 1,
"world" => 2,
"!" => 3 );
// iterate over key-value pairs
foreach($pairs as $k => $v) {
echo "(k,v) = ($k, $v)\n";
}
// iterate over keys
foreach(array_keys($pairs) as $key) {
echo "key = $key, value = $pairs[$key]\n";
}
// iterate over values
foreach($pairs as $value) {
echo "values = $value\n";
}
?>

View file

@ -0,0 +1,32 @@
#! /usr/bin/perl
use strict;
my %pairs = ( "hello" => 13,
"world" => 31,
"!" => 71 );
# iterate over pairs
# Be careful when using each(), however, because it uses a global iterator
# associated with the hash. If you call keys() or values() on the hash in the
# middle of the loop, the each() iterator will be reset to the beginning. If
# you call each() on the hash somewhere in the middle of the loop, it will
# skip over elements for the "outer" each(). Only use each() if you are sure
# that the code inside the loop will not call keys(), values(), or each().
while ( my ($k, $v) = each %pairs) {
print "(k,v) = ($k, $v)\n";
}
# iterate over keys
foreach my $key ( keys %pairs ) {
print "key = $key, value = $pairs{$key}\n";
}
# or (see note about each() above)
while ( my $key = each %pairs) {
print "key = $key, value = $pairs{$key}\n";
}
# iterate over values
foreach my $val ( values %pairs ) {
print "value = $val\n";
}

View file

@ -0,0 +1,12 @@
(put 'A 'foo 5)
(put 'A 'bar 10)
(put 'A 'baz 15)
: (getl 'A) # Get the whole property list
-> ((15 . baz) (10 . bar) (5 . foo))
: (mapcar cdr (getl 'A)) # Get all keys
-> (baz bar foo)
: (mapcar car (getl 'A)) # Get all values
-> (15 10 5)

View file

@ -0,0 +1,12 @@
(idx 'A (def "foo" 5) T)
(idx 'A (def "bar" 10) T)
(idx 'A (def "baz" 15) T)
: A # Get the whole tree
-> ("foo" ("bar" NIL "baz"))
: (idx 'A) # Get all keys
-> ("bar" "baz" "foo")
: (mapcar val (idx 'A)) # Get all values
-> (10 15 5)

View file

@ -0,0 +1,18 @@
myDict = { "hello": 13,
"world": 31,
"!" : 71 }
# iterating over key-value pairs:
for key, value in myDict.items():
print ("key = %s, value = %s" % (key, value))
# iterating over keys:
for key in myDict:
print ("key = %s" % key)
# (is a shortcut for:)
for key in myDict.keys():
print ("key = %s" % key)
# iterating over values:
for value in myDict.values():
print ("value = %s" % value)

View file

@ -0,0 +1,3 @@
> env <- new.env()
> env[["x"]] <- 123
> env[["x"]]

View file

@ -0,0 +1,5 @@
> index <- "1"
> env[[index]] <- "rainfed hay"
> for (name in ls(env)) {
+ cat(sprintf('index=%s, value=%s\n', name, env[[name]]))
+ }

View file

@ -0,0 +1,2 @@
> x <- c(hello=1, world=2, "!"=3)
> print(x["!"])

View file

@ -0,0 +1 @@
> print(unname(x["!"]))

View file

@ -0,0 +1,2 @@
> a <- list(a=1, b=2, c=3.14, d="xyz")
> print(a$a)

View file

@ -0,0 +1 @@
> print(a$d)

View file

@ -0,0 +1,59 @@
/*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 it has
been set.
*/
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). */
/*nice to be in alphabetic 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'
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) /*list all capitals that were set*/
q=word(stateL,j)
say 'the former capital of ('q")" stateN.q "was" stateC.q
end /*j*/
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

View file

@ -0,0 +1,10 @@
#lang racket
(define dict1 #hash((apple . 5) (orange . 10))) ; hash table
(define dict2 '((apple . 5) (orange . 10))) ; a-list
(define dict3 (vector "a" "b" "c")) ; vector (integer keys)
(dict-keys dict1) ; => '(orange apple)
(dict-values dict2) ; => '(5 10)
(for/list ([(k v) (in-dict dict3)]) ; => '("0 -> a" "1 -> b" "2 -> c")
(format "~a -> ~a" k v))

View file

@ -0,0 +1,14 @@
myDict = { "hello" => 13,
"world" => 31,
"!" => 71 }
# iterating over key-value pairs:
myDict.each {|key, value| puts "key = #{key}, value = #{value}"}
# or
myDict.each_pair {|key, value| puts "key = #{key}, value = #{value}"}
# iterating over keys:
myDict.each_key {|key| puts "key = #{key}"}
# iterating over values:
myDict.each_value {|value| puts "value =#{value}"}

View file

@ -0,0 +1,13 @@
val m=Map("Hello"->13, "world"->31, "!"->71)
println("Keys:")
m.keys foreach println
println("\nValues:")
m.values foreach println
println("\nPairs:")
m foreach println
println("\nKey->Value:")
for((k,v)<-m) println(k+"->"+v)

View file

@ -0,0 +1,18 @@
|pairs|
pairs := Dictionary
from: { 'hello' -> 1. 'world' -> 2. '!' -> 3. 'another!' -> 3 }.
"iterate over keys and values"
pairs keysAndValuesDo: [ :k :v |
('(k, v) = (%1, %2)' % { k. v }) displayNl
].
"iterate over keys"
pairs keysDo: [ :key |
('key = %1, value = %2' % { key. pairs at: key }) displayNl
].
"iterate over values"
pairs do: [ :value |
('value = %1' % { value }) displayNl
].

View file

@ -0,0 +1,2 @@
(pairs keys) do: [ :k | "..." ].
(pairs values) do: [ :v | "..." ].

View file

@ -0,0 +1,16 @@
array set myAry {
# list items here...
}
# Iterate over keys and values
foreach {key value} [array get myAry] {
puts "$key -> $value"
}
# Iterate over just keys
foreach key [array names myAry] {
puts "key = $key"
}
# There is nothing for directly iterating over just the values
# Use the keys+values version and ignore the keys

View file

@ -0,0 +1,16 @@
set myDict [dict create ...]; # Make the dictionary
# Iterate over keys and values
dict for {key value} $myDict {
puts "$key -> $value"
}
# Iterate over keys
foreach key [dict keys $myDict] {
puts "key = $key"
}
# Iterate over values
foreach value [dict values $myDict] {
puts "value = $value"
}