Dictionary

Dictionary — stores key/value pairs.

Synopsis

class Dictionary
{
    keys;  
    values; 
}

Description

This class stores key/value pairs. Keys and values can be any type, with the limitation that a key cannot be nil. Comparison uses the equal operator, so strings are case-sensitive and numbers of different types with the same value will compare as equal. Insertion and lookup complexity are approximately O(log2(N)).

Methods

add((key, value)

Adds a new entry to the dictionary, and returns value. Throws an error if the key already exists in the dictionary.

contains(key)

Returns non-nil if the key is in the dictionary, otherwise nil.

get(key)

Returns the value at the key, or throws an error if the key does not exist in the dictionary.

remove(key)

Removes the (key,value) pair for the key and returns non-nil. Throws an error if the key does not exist in the dictionary.

set(key, value)

Changes the value for the key, or throws an error if the key does not exist in the dictionary.

dictionary[key]

Retrieves a value in the dictionary at the key, using the syntax of array access. Returns the value at the key, or nil if the key does not exist in the dictionary. This access does not throw an error if the key does not exist.

dictionary[key] = value

Sets the entry in the dictionary at the key to the value using the syntax of array assignment. Returns the value. If the key does not exist, it is added to the dictionary, otherwise the existing value is replaced. This assignment does not throw an error if the key does not exist.

Instance Variables

keys

An array of all keys currently present in the dictionary.

values

An array of all values currently present in the dictionary, with the same length and in the same order as keys.

Examples

Using methods:

--> D = new(Dictionary)
{Dictionary (keys . []) (values . [])}
--> D.add("k1", 5)
5
--> D.add("k2", "value2")
"value2"
--> D.get("k2")
"value2"
--> D.contains("k1")
t
--> D.set("k1", 22)
22
--> D.keys
["k1" "k2"]
--> D.values
[22 "value2"]
		

Using array notation:

--> D[44] = "some value"
"some value"
--> D[45] = "another value"
"another value"
--> D["k3"] = 15
15
--> D["k1"]
22
--> D
{Dictionary (keys . [44 45 "k1" "k2" "k3"])
	    (values . ["some value" "another value" 22 "value2" 15])}