Add all the A tasks
This commit is contained in:
parent
2dd7375f96
commit
051504d65b
1608 changed files with 18584 additions and 0 deletions
5
Task/Associative-array-Creation/0DESCRIPTION
Normal file
5
Task/Associative-array-Creation/0DESCRIPTION
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
In this task, the goal is to create an [[associative array]] (also known as a dictionary, map, or hash).
|
||||
|
||||
Related tasks:
|
||||
* [[Associative arrays/Iteration]]
|
||||
* [[Hash from two arrays]]
|
||||
4
Task/Associative-array-Creation/1META.yaml
Normal file
4
Task/Associative-array-Creation/1META.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
---
|
||||
category:
|
||||
- Data Structures
|
||||
note: Basic language learning
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
main:(
|
||||
|
||||
MODE COLOR = BITS;
|
||||
FORMAT color repr = $"16r"16r6d$;
|
||||
|
||||
# This is an associative array which maps strings to ints #
|
||||
MODE ITEM = STRUCT(STRING key, COLOR value);
|
||||
REF[]ITEM color map items := LOC[0]ITEM;
|
||||
|
||||
PROC color map find = (STRING color)REF COLOR:(
|
||||
REF COLOR out;
|
||||
# linear search! #
|
||||
FOR index FROM LWB key OF color map items TO UPB key OF color map items DO
|
||||
IF color = key OF color map items[index] THEN
|
||||
out := value OF color map items[index]; GO TO found
|
||||
FI
|
||||
OD;
|
||||
NIL EXIT
|
||||
found:
|
||||
out
|
||||
);
|
||||
|
||||
PROC color map = (STRING color)REF COLOR:(
|
||||
REF COLOR out = color map find(color);
|
||||
IF out :=: REF COLOR(NIL) THEN # extend color map array #
|
||||
HEAP[UPB key OF color map items + 1]ITEM color map append;
|
||||
color map append[:UPB key OF color map items] := color map items;
|
||||
color map items := color map append;
|
||||
value OF (color map items[UPB value OF color map items] := (color, 16r000000)) # black #
|
||||
ELSE
|
||||
out
|
||||
FI
|
||||
);
|
||||
|
||||
# First, populate it with some values #
|
||||
color map("red") := 16rff0000;
|
||||
color map("green") := 16r00ff00;
|
||||
color map("blue") := 16r0000ff;
|
||||
color map("my favourite color") := 16r00ffff;
|
||||
|
||||
# then, get some values out #
|
||||
COLOR color := color map("green"); # color gets 16r00ff00 #
|
||||
color := color map("black"); # accessing unassigned values assigns them to 16r0 #
|
||||
|
||||
# get some value out without accidentally inserting new ones #
|
||||
REF COLOR value = color map find("green");
|
||||
IF value :=: REF COLOR(NIL) THEN
|
||||
put(stand error, ("color not found!", new line))
|
||||
ELSE
|
||||
printf(($"green: "f(color repr)l$, value))
|
||||
FI;
|
||||
|
||||
# Now I changed my mind about my favourite color, so change it #
|
||||
color map("my favourite color") := 16r337733;
|
||||
|
||||
# print out all defined colors #
|
||||
FOR index FROM LWB color map items TO UPB color map items DO
|
||||
ITEM item = color map items[index];
|
||||
putf(stand error, ($"color map("""g""") = "f(color repr)l$, item))
|
||||
OD;
|
||||
|
||||
FORMAT fmt;
|
||||
FORMAT comma sep = $"("n(UPB color map items-1)(f(fmt)", ")f(fmt)")"$;
|
||||
|
||||
fmt := $""""g""""$;
|
||||
printf(($g$,"keys: ", comma sep, key OF color map items, $l$));
|
||||
fmt := color repr;
|
||||
printf(($g$,"values: ", comma sep, value OF color map items, $l$))
|
||||
|
||||
)
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
⍝ Create a namespace ("hash")
|
||||
X←⎕NS ⍬
|
||||
|
||||
⍝ Assign some names
|
||||
X.this←'that'
|
||||
X.foo←88
|
||||
|
||||
⍝ Access the names
|
||||
X.this
|
||||
that
|
||||
|
||||
⍝ Or do it the array way
|
||||
X.(foo this)
|
||||
88 that
|
||||
|
||||
⍝ Namespaces are first class objects
|
||||
sales ← ⎕NS ⍬
|
||||
sales.(prices quantities) ← (100 98.4 103.4 110.16) (10 12 8 10)
|
||||
sales.(revenue ← prices +.× quantities)
|
||||
sales.revenue
|
||||
4109.6
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
BEGIN {
|
||||
a["red"] = 0xff0000
|
||||
a["green"] = 0x00ff00
|
||||
a["blue"] = 0x0000ff
|
||||
for (i in a) {
|
||||
printf "%8s %06x\n", i, a[i]
|
||||
}
|
||||
# deleting a key/value
|
||||
delete a["red"]
|
||||
for (i in a) {
|
||||
print i
|
||||
}
|
||||
# check if a key exists
|
||||
print ( "red" in a ) # print 0
|
||||
print ( "blue" in a ) # print 1
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
var map:Object = {key1: "value1", key2: "value2"};
|
||||
trace(map['key1']); // outputs "value1"
|
||||
|
||||
// Dot notation can also be used
|
||||
trace(map.key2); // outputs "value2"
|
||||
|
||||
// More keys and values can then be added
|
||||
map['key3'] = "value3";
|
||||
trace(map['key3']); // outputs "value3"
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
with Ada.Containers.Ordered_Maps;
|
||||
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
|
||||
with Ada.Text_IO;
|
||||
|
||||
procedure Associative_Array is
|
||||
|
||||
-- Instantiate the generic package Ada.Containers.Ordered_Maps
|
||||
|
||||
package Associative_Int is new Ada.Containers.Ordered_Maps(Unbounded_String, Integer);
|
||||
use Associative_Int;
|
||||
|
||||
Color_Map : Map;
|
||||
Color_Cursor : Cursor;
|
||||
Success : Boolean;
|
||||
Value : Integer;
|
||||
begin
|
||||
|
||||
-- Add values to the ordered map
|
||||
|
||||
Color_Map.Insert(To_Unbounded_String("Red"), 10, Color_Cursor, Success);
|
||||
Color_Map.Insert(To_Unbounded_String("Blue"), 20, Color_Cursor, Success);
|
||||
Color_Map.Insert(To_Unbounded_String("Yellow"), 5, Color_Cursor, Success);
|
||||
|
||||
-- retrieve values from the ordered map and print the value and key
|
||||
-- to the screen
|
||||
|
||||
Value := Color_Map.Element(To_Unbounded_String("Red"));
|
||||
Ada.Text_Io.Put_Line("Red:" & Integer'Image(Value));
|
||||
Value := Color_Map.Element(To_Unbounded_String("Blue"));
|
||||
Ada.Text_IO.Put_Line("Blue:" & Integer'Image(Value));
|
||||
Value := Color_Map.Element(To_Unbounded_String("Yellow"));
|
||||
Ada.Text_IO.Put_Line("Yellow:" & Integer'Image(Value));
|
||||
end Associative_Array;
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
var names = {} // empty map
|
||||
names["foo"] = "bar"
|
||||
names[3] = 4
|
||||
|
||||
// initialized map
|
||||
var names2 = {"foo": bar, 3:4}
|
||||
|
||||
// lookup map
|
||||
var name = names["foo"]
|
||||
if (typeof(name) == "none") {
|
||||
println ("not found")
|
||||
} else {
|
||||
println (name)
|
||||
}
|
||||
|
||||
// remove from map
|
||||
delete names["foo"]
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
associative_array := {key1: "value 1", "Key with spaces and non-alphanumeric characters !*+": 23}
|
||||
MsgBox % associative_array["key1"]
|
||||
. "`n" associative_array["Key with spaces and non-alphanumeric characters !*+"]
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
arrayX1 = first
|
||||
arrayX2 = second
|
||||
arrayX3 = foo
|
||||
arrayX4 = bar
|
||||
Loop, 4
|
||||
Msgbox % arrayX%A_Index%
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
{:key "value"
|
||||
:key2 "value2"
|
||||
:key3 "value3"}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
-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(dict:store(foo,3,D2)).
|
||||
|
||||
print_vals(D) ->
|
||||
lists:foreach(fun (K) ->
|
||||
io:format("~p: ~b~n",[K,dict:fetch(K,D)])
|
||||
end, dict:fetch_keys(D)).
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
: get ( key len table -- data ) \ 0 if not present
|
||||
search-wordlist if
|
||||
>body @
|
||||
else 0 then ;
|
||||
|
||||
: put ( data key len table -- )
|
||||
>r 2dup r@ search-wordlist if
|
||||
r> drop nip nip
|
||||
>body !
|
||||
else
|
||||
r> get-current >r set-current \ switch definition word lists
|
||||
nextname create ,
|
||||
r> set-current
|
||||
then ;
|
||||
wordlist constant bar
|
||||
5 s" alpha" bar put
|
||||
9 s" beta" bar put
|
||||
2 s" gamma" bar put
|
||||
s" alpha" bar get . \ 5
|
||||
8 s" Alpha" bar put \ Forth dictionaries are normally case-insensitive
|
||||
s" alpha" bar get . \ 8
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
include ffl/hct.fs
|
||||
|
||||
\ Create a hash table 'table' in the dictionary with a starting size of 10
|
||||
|
||||
10 hct-create htable
|
||||
|
||||
\ Insert entries
|
||||
|
||||
5 s" foo" htable hct-insert
|
||||
10 s" bar" htable hct-insert
|
||||
15 s" baz" htable hct-insert
|
||||
|
||||
\ Get entry from the table
|
||||
|
||||
s" bar" htable hct-get [IF]
|
||||
.( Value:) . cr
|
||||
[ELSE]
|
||||
.( Entry not present.) cr
|
||||
[THEN]
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
// declare a nil map variable, for maps from string to int
|
||||
var x map[string] int
|
||||
|
||||
// make an empty map
|
||||
x = make(map[string] int)
|
||||
|
||||
// make an empty map with an initial capacity
|
||||
x = make(map[string] int, 42)
|
||||
|
||||
// set a value
|
||||
x["foo"] = 3
|
||||
|
||||
// make a map with a literal
|
||||
x = map[string] int {
|
||||
"foo": 2, "bar": 42, "baz": -1,
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
import Data.Map
|
||||
|
||||
dict = fromList [("key1","val1"), ("key2","val2")]
|
||||
|
||||
ans = Data.Map.lookup "key2" dict -- evaluates to "val2"
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
dict = [("key1","val1"), ("key2","val2")]
|
||||
|
||||
ans = lookup "key2" dict -- evaluates to Just "val2"
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
Map<String, Integer> map = new HashMap<String, Integer>();
|
||||
map.put("foo", 5);
|
||||
map.put("bar", 10);
|
||||
map.put("baz", 15);
|
||||
map.put("foo", 6);
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
public static Map<String, Integer> map = new HashMap<String, Integer>(){{
|
||||
put("foo", 5);
|
||||
put("bar", 10);
|
||||
put("baz", 15);
|
||||
put("foo", 6);
|
||||
}};
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
map.get("foo"); // => 5
|
||||
map.get("invalid"); // => null
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
for (String key: map.keySet())
|
||||
System.out.println(key);
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
for (int value: map.values())
|
||||
System.out.println(value);
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
for (Map.Entry<String, Integer> entry: map.entrySet())
|
||||
System.out.println(entry.getKey() + " => " + entry.getValue());
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
var assoc = {};
|
||||
assoc['foo'] = 'bar';
|
||||
assoc['another-key'] = 3;
|
||||
assoc.thirdKey = 'we can also do this!'; // dot notation can be used if the property name
|
||||
// is a valid identifier
|
||||
assoc[2] = 'the index here is the string "2"';
|
||||
assoc[null] = 'this also works';
|
||||
assoc[(function(){return 'expr';})()] = 'Can use expressions too';
|
||||
|
||||
for (var key in assoc) {
|
||||
if (assoc.hasOwnProperty(key)) {
|
||||
alert('key:"' + key + '", value:"' + assoc[key] + '"');
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
var assoc = {
|
||||
foo: 'bar',
|
||||
'another-key': 3 //the key can either be enclosed by quotes or not
|
||||
};
|
||||
|
|
@ -0,0 +1 @@
|
|||
'foo' in assoc // true
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
hash = {}
|
||||
hash[ "key-1" ] = "val1"
|
||||
hash[ "key-2" ] = 1
|
||||
hash[ "key-3" ] = {}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
$array = array();
|
||||
$array['foo'] = 'bar';
|
||||
$array['bar'] = 'foo';
|
||||
|
||||
echo($array['foo']); // bar
|
||||
echo($array['moo']); // Undefined index
|
||||
|
||||
//alternative (inline) way
|
||||
$array2 = array('fruit' => 'apple',
|
||||
'price' => 12.96,
|
||||
'colour' => 'green');
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
foreach($array as $key => $value)
|
||||
{
|
||||
echo "Key: $key Value: $value";
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
# using => key does not need to be quoted unless it contains special chars
|
||||
my %hash = (
|
||||
key1 => 'val1',
|
||||
'key-2' => 2,
|
||||
three => -238.83,
|
||||
4 => 'val3',
|
||||
);
|
||||
|
||||
# using , both key and value need to be quoted if containing something non-numeric in nature
|
||||
my %hash = (
|
||||
'key1', 'val1',
|
||||
'key-2', 2,
|
||||
'three', -238.83,
|
||||
4, 'val3',
|
||||
);
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
print $hash{key1};
|
||||
|
||||
$hash{key1} = 'val1';
|
||||
|
||||
@hash{'key1', 'three'} = ('val1', -238.83);
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
my $hashref = {
|
||||
key1 => 'val1',
|
||||
'key-2' => 2,
|
||||
three => -238.83,
|
||||
4 => 'val3',
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
print $hash->{key1};
|
||||
|
||||
$hash->{key1} = 'val1';
|
||||
|
||||
@hash->{'key1', 'three'} = ('val1', -238.83);
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
(put 'A 'foo 5)
|
||||
(put 'A 'bar 10)
|
||||
(put 'A 'baz 15)
|
||||
(put 'A 'foo 20)
|
||||
|
||||
: (get 'A 'bar)
|
||||
-> 10
|
||||
|
||||
: (get 'A 'foo)
|
||||
-> 20
|
||||
|
||||
: (show 'A)
|
||||
A NIL
|
||||
foo 20
|
||||
bar 10
|
||||
baz 15
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
mymap(key1,value1).
|
||||
mymap(key2,value2).
|
||||
|
||||
?- mymap(key1,V).
|
||||
V = value1
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
hash = dict() # 'dict' is the dictionary type.
|
||||
hash = dict(red="FF0000", green="00FF00", blue="0000FF")
|
||||
hash = { 'key1':1, 'key2':2, }
|
||||
value = hash[key]
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
# empty dictionary
|
||||
d = {}
|
||||
d['spam'] = 1
|
||||
d['eggs'] = 2
|
||||
|
||||
# dictionaries with two keys
|
||||
d1 = {'spam': 1, 'eggs': 2}
|
||||
d2 = dict(spam=1, eggs=2)
|
||||
|
||||
# dictionaries from tuple list
|
||||
d1 = dict([('spam', 1), ('eggs', 2)])
|
||||
d2 = dict(zip(['spam', 'eggs'], [1, 2]))
|
||||
|
||||
# iterating over keys
|
||||
for key in d:
|
||||
print key, d[key]
|
||||
|
||||
# iterating over (key, value) pairs
|
||||
for key, value in d.iteritems():
|
||||
print key, value
|
||||
|
|
@ -0,0 +1 @@
|
|||
myDict = { '1': 'a string', 1: 'an integer', 1.0: 'a floating point number', (1,): 'a tuple' }
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
> env <- new.env()
|
||||
> env[["x"]] <- 123
|
||||
> env[["x"]]
|
||||
|
|
@ -0,0 +1 @@
|
|||
> print(names(a))
|
||||
|
|
@ -0,0 +1 @@
|
|||
> print(unname(a))
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
> index <- "1"
|
||||
> env[[index]] <- "rainfed hay"
|
||||
> env[[index]]
|
||||
|
|
@ -0,0 +1 @@
|
|||
> env[["1"]]
|
||||
|
|
@ -0,0 +1 @@
|
|||
> env
|
||||
|
|
@ -0,0 +1 @@
|
|||
> print(env)
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
> x <- c(hello=1, world=2, "!"=3)
|
||||
> print(x)
|
||||
|
|
@ -0,0 +1 @@
|
|||
> print(names(x))
|
||||
|
|
@ -0,0 +1 @@
|
|||
print(unname(x))
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
> a <- list(a=1, b=2, c=3.14, d="xyz")
|
||||
> print(a)
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
/* Rexx */
|
||||
|
||||
key0 = '0'
|
||||
key1 = 'key0'
|
||||
|
||||
stem. = '.' /* Initialize the associative array 'stem' to '.' */
|
||||
stem.key1 = 'value0' /* Set a specific key/value pair */
|
||||
|
||||
Say '<stem key="'key0'" value="'stem.key0'" />' /* Display a value for a key that wasn't set */
|
||||
Say '<stem key="'key1'" value="'stem.key1'" />' /* Display a value for a key that was set */
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
/*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). │
|
||||
└────────────────────────────────────────────────────────────────────┘*/
|
||||
stateC.=' [not defined yet] ' /*sets any/all state capitols. */
|
||||
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, ...).│
|
||||
└────────────────────────────────────────────────────────────────────┘*/
|
||||
stateC.ca='Sacramento'; stateN.ca='California'
|
||||
stateC.nd='Bismarck' ; stateN.nd='North Dakota'
|
||||
stateC.mn='St. Paul' ; stateN.mn='Minnesota'
|
||||
stateC.dc='Washington'; stateN.dc='District of Columbia'
|
||||
stateC.ri='Providence'; stateN.ri='Rhode Island and Providence Plantations
|
||||
|
||||
say 'capital of California is' stateC.ca
|
||||
say 'capital of Oklahoma is' stateC.ok
|
||||
yyy='RI'
|
||||
say 'capital of' stateN.yyy "is" stateC.yyy
|
||||
/*stick a fork in it, we're done.*/
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
#lang racket
|
||||
|
||||
;; a-lists
|
||||
(define a-list '((a . 5) (b . 10)))
|
||||
(assoc a-list 'a) ; => '(a . 5)
|
||||
|
||||
;; hash tables
|
||||
(define table #hash((a . 5) (b . 10)))
|
||||
(hash-ref table 'a) ; => 5
|
||||
|
||||
;; dictionary interface
|
||||
(dict-ref a-list 'a) ; => 5
|
||||
(dict-ref table 'a) ; => 5
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
hash={}
|
||||
hash[666]='devil'
|
||||
hash[777] # => nil
|
||||
hash[666] # => 'devil'
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
hash=Hash.new('unknown key')
|
||||
hash[666]='devil'
|
||||
hash[777] # => 'unknown key'
|
||||
hash[666] # => 'devil'
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
hash=Hash.new{|h,k| "unknown key #{k}"}
|
||||
hash[666]='devil'
|
||||
hash[777] # => 'unknown key 777'
|
||||
hash[666] # => 'devil'
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
hash=Hash.new{|h,k|h[k]="key #{k} was added at #{Time.now}"}
|
||||
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'
|
||||
hash[555] # => 'key 555 was added at Sun Apr 03 13:50:01 -0700 2011'
|
||||
hash[777] # => 'key 777 was added at Sun Apr 03 13:49:57 -0700 2011'
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
class MAIN is
|
||||
main is
|
||||
-- creation of a map between strings and integers
|
||||
map ::= #MAP{STR, INT};
|
||||
|
||||
-- add some values
|
||||
map := map.insert("red", 0xff0000);
|
||||
map := map.insert("green", 0xff00);
|
||||
map := map.insert("blue", 0xff);
|
||||
|
||||
#OUT + map + "\n"; -- show the map...
|
||||
|
||||
-- test if "indexes" exist
|
||||
#OUT + map.has_ind("red") + "\n";
|
||||
#OUT + map.has_ind("carpet") + "\n";
|
||||
|
||||
-- retrieve a value by index
|
||||
#OUT + map["green"] + "\n";
|
||||
end;
|
||||
end;
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
// immutable maps
|
||||
var map = Map(1 -> 2, 3 -> 4, 5 -> 6)
|
||||
map(3) // 4
|
||||
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements
|
||||
map.isDefinedAt(33) // false
|
||||
map.isDefinedAt(44) // true
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
// mutable maps (HashSets)
|
||||
import scala.collection.mutable.HashMap
|
||||
val hash = new HashMap[int, int]
|
||||
hash(1) = 2
|
||||
hash += (1 -> 2) // same as hash(1) = 2
|
||||
hash += (3 -> 4, 5 -> 6, 44 -> 99)
|
||||
hash(44) // 99
|
||||
hash.contains(33) // false
|
||||
hash.isDefinedAt(33) // same as contains
|
||||
hash.contains(44) // true
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
// iterate over key/value
|
||||
hash.foreach {e => println("key "+e._1+" value "+e._2)} // e is a 2 element Tuple
|
||||
// same with for syntax
|
||||
for((k,v) <- hash) println("key " + k + " value " + v)
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
// items in map where the key is greater than 3
|
||||
map.filter {k => k._1 > 3} // Map(5 -> 6, 44 -> 99)
|
||||
// same with for syntax
|
||||
for((k, v) <- map; if k > 3) yield (k,v)
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
(define my-dict '((a b) (1 hello) ("c" (a b c)))
|
||||
(assoc 'a my-dict) ; evaluates to '(a b)
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
(define my-alist '((a b) (1 hello) ("c" (a b c)))
|
||||
(define my-hash (alist->hash-table my-alist))
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
states := Dictionary new.
|
||||
states at: 'MI' put: 'Michigan'.
|
||||
states at: 'MN' put: 'Minnesota'.
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
# Create one element at a time:
|
||||
set hash(foo) 5
|
||||
|
||||
# Create in bulk:
|
||||
array set hash {
|
||||
foo 5
|
||||
bar 10
|
||||
baz 15
|
||||
}
|
||||
|
||||
# Access one element:
|
||||
set value $hash(foo)
|
||||
|
||||
# Output all values:
|
||||
foreach key [array names hash] {
|
||||
puts $hash($key)
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
# Create in bulk
|
||||
set d [dict create foo 5 bar 10 baz 15]
|
||||
|
||||
# Create/update one element
|
||||
dict set d foo 5
|
||||
|
||||
# Access one value
|
||||
set value [dict get $d foo]
|
||||
|
||||
# Output all values
|
||||
dict for {key value} $d {
|
||||
puts $value
|
||||
}
|
||||
# Alternatively...
|
||||
foreach value [dict values $d] {
|
||||
puts $value
|
||||
}
|
||||
|
||||
# Output the whole dictionary (since it is a Tcl value itself)
|
||||
puts $d
|
||||
Loading…
Add table
Add a link
Reference in a new issue