Associative array/Creation: Difference between revisions

Content added Content deleted
(Added LFE example)
(→‎{{header|Common Lisp}}: add chapel version)
Line 553: Line 553:
(defparameter *legs* '((cow . 4) (flamingo . 2) (centipede . 100)))
(defparameter *legs* '((cow . 4) (flamingo . 2) (centipede . 100)))
;; you can use assoc to do lookups and cons new elements onto it to make it longer.</lang>
;; you can use assoc to do lookups and cons new elements onto it to make it longer.</lang>

=={{header|Chapel}}==

In Chapel, associative arrays are regular arrays with a non-integer domain - values used as keys into the array.
The creation of the domain is independent from the creation of the array, and in fact the same domain can be used for multiple arrays, creating associative arrays with identical sets of keys. When the domain is changed, all arrays that use it will be reallocated.

<lang>// arr is an array of string to int. any type can be used in both places.
var keys: domain(string);
var arr: [keys] int;

// keys can be added to a domain using +, new values will be initialized to the default value (0 for int)
keys += "foo";
keys += "bar";
keys += "baz";

// array access via [] or ()
arr["foo"] = 1;
arr["bar"] = 4;
arr("baz") = 6;

// write auto-formats domains and arrays
writeln("Keys: ", keys);
writeln("Values: ", arr);

// keys can be deleted using -
keys -= "bar";

writeln("Keys: ", keys);
writeln("Values: ", arr);</lang>

{{out}}
Keys: {foo, bar, baz}
Values: 1 4 6
Keys: {foo, baz}
Values: 1 6


=={{header|D}}==
=={{header|D}}==