Associative array/Creation: Difference between revisions

m
→‎{{header|Sidef}}: simplifications
(Add Ecstasy example)
m (→‎{{header|Sidef}}: simplifications)
(16 intermediate revisions by 11 users not shown)
Line 2,087:
("baz" 77)) ls2map !</syntaxhighlight>
 
=={{header|BaConBASIC}}==
==={{header|BaCon}}===
<syntaxhighlight lang="qbasic">DECLARE associative ASSOC STRING
 
Line 2,102 ⟶ 2,103:
String keys, with ASSOC to a given data type. Sizing is dynamic.
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">global values$, keys$
dim values$[1]
Line 2,218 ⟶ 2,219:
e endive
c carrot</pre>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> REM Store some values with their keys:
PROCputdict(mydict$, "FF0000", "red")
PROCputdict(mydict$, "00FF00", "green")
PROCputdict(mydict$, "0000FF", "blue")
REM Retrieve some values using their keys:
PRINT FNgetdict(mydict$, "green")
PRINT FNgetdict(mydict$, "red")
END
DEF PROCputdict(RETURN dict$, value$, key$)
IF dict$ = "" dict$ = CHR$(0)
dict$ += key$ + CHR$(1) + value$ + CHR$(0)
ENDPROC
DEF FNgetdict(dict$, key$)
LOCAL I%, J%
I% = INSTR(dict$, CHR$(0) + key$ + CHR$(1))
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
J% = INSTR(dict$, CHR$(0), I%)
= MID$(dict$, I%, J% - I%)</syntaxhighlight>
 
=={{header|Batch File}}==
Line 2,257 ⟶ 2,281:
"sicko&mumps" = 7
"sicko&bromodrosis" = 8</pre>
 
=={{header|BBC BASIC}}==
<syntaxhighlight lang="bbcbasic"> REM Store some values with their keys:
PROCputdict(mydict$, "FF0000", "red")
PROCputdict(mydict$, "00FF00", "green")
PROCputdict(mydict$, "0000FF", "blue")
REM Retrieve some values using their keys:
PRINT FNgetdict(mydict$, "green")
PRINT FNgetdict(mydict$, "red")
END
DEF PROCputdict(RETURN dict$, value$, key$)
IF dict$ = "" dict$ = CHR$(0)
dict$ += key$ + CHR$(1) + value$ + CHR$(0)
ENDPROC
DEF FNgetdict(dict$, key$)
LOCAL I%, J%
I% = INSTR(dict$, CHR$(0) + key$ + CHR$(1))
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
J% = INSTR(dict$, CHR$(0), I%)
= MID$(dict$, I%, J% - I%)</syntaxhighlight>
 
=={{header|Bracmat}}==
Line 2,747 ⟶ 2,748:
["one" => 2].diverge(String, float64) # mutable, initial contents,
# typed (coerces to float)</syntaxhighlight>
=={{header|EasyLang}}==
<syntaxhighlight>
# use array of array for this
proc hashGet ind$ . ar$[][] item$ .
for i to len ar$[][]
if ar$[i][1] = ind$
item$ = ar$[i][2]
return
.
.
item$ = ""
.
proc hashSet ind$ val$ . ar$[][] .
for i to len ar$[][]
if ar$[i][1] = ind$
ar$[i][2] = val$
return
.
.
.
clothing$[][] = [ [ "type" "t-shirt" ] [ "color" "red" ] ]
clothing$[][] &= [ "size" "xl" ]
#
hashSet "color" "green" clothing$[][]
hashGet "color" clothing$[][] col$
print col$
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Line 2,782 ⟶ 2,810:
<syntaxhighlight lang="java">Int? mightBeNull = map["foo"];
Int neverNull = map.getOrDefault("foo", 0);
if (Int n := map.get("foo")) {
{
// if "foo" is in the map, then the variable "n" is set to its value
} else {
}
else
{
// if "foo" is not in the map, then the variable "n" is not defined
}</syntaxhighlight>
Iterate over keys:
<syntaxhighlight lang="java">for (String key : map) {
{
// the variable "key" is defined here
}</syntaxhighlight>
Iterate over values:
<syntaxhighlight lang="java">for (Int value : map.values) {
{
// the variable "value" is defined here
}</syntaxhighlight>
Iterate over key, value pairs:
<syntaxhighlight lang="java">for ((String skey, Int ivalue) : map) {
{
// the variables "key" and "value" are defined here
}</syntaxhighlight>
 
=={{header|Elena}}==
Line 2,836 ⟶ 2,858:
 
=={{header|Elixir}}==
===Map literals===
An empty map:
 
<syntaxhighlight lang="elixir">
%{}
</syntaxhighlight>
 
A map with key-value pairs of different types:
 
<syntaxhighlight lang="elixir">
%{"one" => :two, 3 => "four"}
</syntaxhighlight>
 
Maps with atoms as keys:
 
<syntaxhighlight lang="elixir">
%{a: 1, b: 2}
# equivalent to
%{:a => 1, :b => 2}
</syntaxhighlight>
 
===Programmatic map creation===
{{trans|Erlang}}
<syntaxhighlight lang="elixir">defmodule RC do
Line 2,876 ⟶ 2,920:
 
<code>define-hash-table-test</code> can create other key comparison types.
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
Map empty = Map(int, text) # creates an empty map
writeLine(empty)
var longFruit = Map(int, text).of(1, "banana") # creates a map with the pair 1 => "banana"
longFruit[2] = "melon" # associates a key of 2 with "melon"
longFruit.insert(3, "avocado")
writeLine(longFruit) # prints the map
var shortFruit = int%text[4 => "kiwi", 5 => "apple"] # map creation using arrow notation
writeLine(shortFruit[5]) # retrieves the value with a key of 5 and prints it out
writeLine(shortFruit.length) # prints the number of entries
writeLine(shortFruit) # prints the map
writeLine(text%text["Italy" => "Rome", "France" => "Paris", "Germany" => "Berlin", "Spain" => "Madrid"])
 
</syntaxhighlight>
{{out}}
<pre>
[]
[1:banana,2:melon,3:avocado]
apple
2
[4:kiwi,5:apple]
[Italy:Rome,France:Paris,Germany:Berlin,Spain:Madrid]
</pre>
 
=={{header|Erlang}}==
Line 3,153 ⟶ 3,222:
=={{header|Futhark}}==
<syntaxhighlight lang="futhark">let associative_array = {key1=1,key2=2}</syntaxhighlight>
 
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
void local fn DoIt
CFDictionaryRef dict1 = fn DictionaryWithObjects( @"Alpha", @"A", @"Bravo", @"B", @"Charlie", @"C", @"Delta", @"D", NULL )
CFDictionaryRef dict2 = @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"}
CFMutableDictionaryRef dict3 = fn MutableDictionaryWithCapacity(0)
MutableDictionarySetObjectForKey( dict3, @"Alpha", @"A" )
MutableDictionarySetObjectForKey( dict3, @"Bravo", @"B" )
MutableDictionarySetObjectForKey( dict3, @"Charlie", @"C" )
MutableDictionarySetObjectForKey( dict3, @"Delta", @"D" )
CFMutableDictionaryRef dict4 = fn MutableDictionaryWithDictionary( @{@"A":@"Alpha", @"B":@"Bravo", @"C":@"Charlie", @"D":@"Delta"} )
print fn DictionaryObjectForKey( dict1, @"A" )
print dict1[@"B"]
print dict2[@"C"]
print dict3[@"D"]
print dict4
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
Alpha
Bravo
Charlie
Delta
{
A = Alpha;
B = Bravo;
C = Charlie;
D = Delta;
}
</pre>
 
=={{header|Gambas}}==
Line 3,329 ⟶ 3,440:
say "'baz' => [V].";
end the story.</syntaxhighlight>
 
=={{header|Insitux}}==
 
It is possible to use any value type for both keys and values for a dictionary in Insitux.
 
<syntaxhighlight lang="insitux">{
:a "value" ;keyword key, string value
:b 123 ;keyword key, number value
456 [1 2 3] ;number key, vector value
[5 6 7] :b ;vector key, keyword value
{:a 1} {:b 2} ;dictionary key, dictionary value
}</syntaxhighlight>
 
<syntaxhighlight lang="insitux">;use dictionary as function for lookup; commas for readability, treated as white-space
> ({:a 1, :b 2, :c 3} :b)
2</syntaxhighlight>
 
<syntaxhighlight lang="insitux">;extend existing dictionary by using it as a function with two arguments
> ({:a 1, :b 2, :c 3} :b 3)
{:a 1, :b 3, :c 3}</syntaxhighlight>
 
=={{header|Ioke}}==
Line 3,363 ⟶ 3,494:
Note that J's symbols (http://www.jsoftware.com/help/dictionary/dsco.htm) might also be used for this purpose. However, symbols are not garbage collected within a J session (and, instead, a mechanism is provided to optionally preserve them across sessions).
 
=={{header|JavaJakt}}==
<syntaxhighlight lang="jakt">
{{works with|Java|1.5+}}
fn main() {
 
let dictionary = ["foo": 1, "bar": 2]
Defining the Map:
println("{}", dictionary)
<syntaxhighlight lang="java5">Map<String, Integer> map = new HashMap<String, Integer>();
}
map.put("foo", 5);
</syntaxhighlight>
map.put("bar", 10);
map.put("baz", 15);
map.put("foo", 6);</syntaxhighlight>
"Putting" a value for a key that already exists ("map.put("foo", 6)" in this example) will replace and return the old value for the key.
 
=={{header|Java}}==
Initializing a Map as a class member:
<p>
<syntaxhighlight lang="java5">public static Map<String, Integer> map = new HashMap<String, Integer>(){{
Java offers an associative array, referred to as a <code>Map</code>, as part of the Collections Framework.<br />
put("foo", 5);
There are numerous implementing classes, each which provide unique functionality for various tasks.<br />
put("bar", 10);
</p>
put("baz", 15);
<p>
put("foo", 6);
It's worth noting that Java also offers the <code>Dictionary</code> class, which appears to be less preferred, according to Java.<br />
}};</syntaxhighlight>
<kbd><i>"[The Map] interface takes the place of the Dictionary class ..."</i></kbd>.
Retrieving a value:
</p>
<syntaxhighlight lang="java5">map.get("foo"); // => 6
<p>
map.get("invalid"); // => null</syntaxhighlight>
Note that it is possibleThe tomost putgeneralized <code>nullMap</code> aswould abe value, sothe <code>nullHashMap</code>, being returned by <code>get</code>which is nota sufficientbasic, forunordered, determiningset that the key is not in theof <codekbd>Mapkeys</codekbd>. There is aand <codekbd>containsKeyvalues</codekbd> method for that.<br />
There is also the <code>LinkedHashMap</code>, which will preserve the order of input.<br />
 
There is the <code>TreeMap</code>, which is used to store the <kbd>key</kbd>s in a specific order, using the <kbd>key</kbd>'s <code>compareTo</code> method.
Iterate over keys:
Optionally, you could provide your own <kbd>comparator</kbd> using the <code>Comparator</code> interface, which I'll demonstrate below.<br />
<syntaxhighlight lang="java5">for (String key: map.keySet())
There are numerous other implementing classes, which can be found under the <code>Map</code> <kbd>Javadoc</kbd>,
System.out.println(key);</syntaxhighlight>
[https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/Map.html. Map (Java SE 20 & JDK 20)].
Iterate over values:
</p>
<syntaxhighlight lang="java5">for (int value: map.values())
<p>
System.out.println(value);</syntaxhighlight>
Here is a basic implementation of a <code>HashMap</code>.
Iterate over key, value pairs:
</p>
<syntaxhighlight lang="java5">for (Map.Entry<String, Integer> entry: map.entrySet())
<syntaxhighlight lang="java">
System.out.println(entry.getKey() + " => " + entry.getValue());</syntaxhighlight>
Map<String, Integer> map = new HashMap<>();
</syntaxhighlight>
<p>
To add a <kbd>key</kbd> and <kbd>value</kbd> pair, you use the <code>Map.put</code> method.<br />
A useful feature of <code>Map.put</code> is that if the <kbd>key</kbd> already exists, thus is being overridden,
it will return the overridden value, otherwise <code>null</code>.
</p>
<syntaxhighlight lang="java">
map.put("rosetta", 100);
map.put("code", 200);
</syntaxhighlight>
<p>
To get a <kbd>value</kbd>, you use the <code>Map.get</code> method, specifying the <kbd>key</kbd> as the parameter.<br />
If the specified <kbd>key</kbd> does not exist, <code>null</code> is returned.
</p>
<syntaxhighlight lang="java">
int valueA = map.get("rosetta");
int valueB = map.get("code");
</syntaxhighlight>
<p>
To mutate a <kbd>key</kbd>'s <kbd>value</kbd>, you use the <code>Map.replace</code> method.
</p>
<syntaxhighlight lang="java">
map.replace("rosetta", 300);
</syntaxhighlight>
<p>
Alternately, you can replace the <kbd>value</kbd>, only if it is of a current <kbd>value</kbd>.<br />
So, in this example it will return <kbd>true</kbd>, only if the <kbd>key</kbd> <kbd><i>"rosetta"</i></kbd> had the current <kbd>value</kbd> of <kbd><i>100</i></kbd>.
</p>
<syntaxhighlight lang="java">
boolean replaced = map.replace("rosetta", 100, 300);
</syntaxhighlight>
<p>
To check for the existence of a <kbd>key</kbd>, you use the <code>containsKey</code> method.
</p>
<syntaxhighlight lang="java">
boolean contains = map.containsKey("rosetta");
</syntaxhighlight>
<p>
And to check for the existence of a <kbd>value</kbd>, you use the <code>containsValue</code> method.
</p>
<syntaxhighlight lang="java">
boolean contains = map.containsValue(100);
</syntaxhighlight>
<p>
A <code>LinkedHashMap</code> is exactly the same as a <code>HashMap</code>, except it will preserve the order in which the <kbd>key</kbd>s were added.
</p>
<syntaxhighlight lang="java">
Map<String, Integer> map = new LinkedHashMap<>();
map.put("rosetta", 100);
map.put("code", 200);
</syntaxhighlight>
<p>
A <code>TreeMap</code> is useful for when you want the <kbd>key</kbd>s in a specific order.<br />
By default, it will use the <kbd>key</kbd>'s <code>compareTo</code> method, to determine the order.<br />
So, if you're <kbd>key</kbd> is a <code>String</code>, the order will be ascending, similar to an actual dictionary.
</p>
<syntaxhighlight lang="java">
Map<String, Integer> map = new TreeMap<>();
map.put("rosetta", 100);
map.put("code", 200);
</syntaxhighlight>
<p>
You could, optionally, specify a comparator by implementing a <code>Comparator</code> interface.<br />
A <code>TreeMap</code>, conveniently, only requires you to implement the <code>compare</code> method of the <code>Comparator</code>,
so the implementation can be done as an <kbd>anonymous class</kbd>.
</p>
<syntaxhighlight lang="java">
Comparator<String> comparator = new Comparator<String>() {
public int compare(String stringA, String stringB) {
if (stringA.compareTo(stringB) > 0) {
return -1;
} else if (stringA.compareTo(stringB) < 0) {
return 1;
}
return 0;
}
};
</syntaxhighlight>
<p>
Which you then supply as an argument to the constructor.
</p>
<syntaxhighlight lang="java">
Map<String, Integer> map = new TreeMap<>(comparator);
</syntaxhighlight>
<p>
To make things even simpler, you could use a <kbd>lambda</kbd> for the <kbd>anonymous class</kbd>.
</p>
<syntaxhighlight lang="java">
Comparator<String> comparator = (stringA, stringB) -> {
if (stringA.compareTo(stringB) > 0) {
return -1;
} else if (stringA.compareTo(stringB) < 0) {
return 1;
}
return 0;
};
</syntaxhighlight>
 
=={{header|JavaScript}}==
Line 5,149 ⟶ 5,375:
 
=={{header|Ruby}}==
===Hash literals===
A hash object that returns [[nil]] for unknown keys
Ruby has literal syntax for Hash objects.
<syntaxhighlight lang="ruby">hash={}
 
hash[666]='devil'
A Hash with symbols as keys:
<syntaxhighlight lang="ruby">
{:name => 'Zeus', :planet => 'Jupiter'}
</syntaxhighlight>
 
Shorthand for symbol keys:
 
<syntaxhighlight lang="ruby">
{name: 'Zeus', planet: 'Jupiter'}
</syntaxhighlight>
 
A Hash with keys and values of arbitrary types:
 
<syntaxhighlight lang="ruby">
{1 => 'two', three: 4}
</syntaxhighlight>
 
An empty Hash:
 
<syntaxhighlight lang="ruby">
{}
</syntaxhighlight>
 
===Customizing the default value===
 
A Hash object that returns [[nil]] for unknown keys:
<syntaxhighlight lang="ruby">hash = {}
hash[666] = 'devil'
hash[777] # => nil
hash[666] # => 'devil'</syntaxhighlight>
 
A hashHash object that returns 'unknown key' for unknown keys:
<syntaxhighlight lang="ruby">hash = Hash.new('unknown key')
hash[666] = 'devil'
hash[777] # => 'unknown key'
hash[666] # => 'devil'</syntaxhighlight>
 
A hashHash object that returns "unknown key #{key}" for unknown keys:
<syntaxhighlight lang="ruby">hash = Hash.new { |h, k| "unknown key #{k}" }
hash[666] = 'devil'
hash[777] # => 'unknown key 777'
hash[666] # => 'devil'</syntaxhighlight>
 
A hashHash object that adds "key #{key} was added at #{Time.now}" to the hash the first time an unknown key is seen:
<syntaxhighlight lang="ruby">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'
Line 5,781 ⟶ 6,035:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var hash = Hash.new(
key1 => 'value1',
key2 => 'value2',
);
 
# Add a new key-value pair
hash{:key3} = 'value3';</syntaxhighlight>
 
=={{header|Slate}}==
Line 6,165 ⟶ 6,419:
=={{header|Wren}}==
Wren has a Map class built in.
<syntaxhighlight lang="ecmascriptwren">var fruit = {} // creates an empty map
fruit[1] = "orange" // associates a key of 1 with "orange"
fruit[2] = "apple" // associates a key of 2 with "apple"
Line 6,194 ⟶ 6,448:
null
</pre>
 
 
=={{header|XLISP}}==
2,747

edits