1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
title:: Key Value Pairs
summary:: An interface for translating between three common data structures: Dictionaries, Arrays of Associations and of Pairs
categories:: Collections, Interfaces
related::Classes/IdentityDictionary, Classes/Array, Classes/Association
SECTION::Motivation
There are three very similar ways to represent maps between keys and values, each of which have a specific purpose:
TABLE::
## key value pairs || common representation of arguments || code::[\freq, 452, \amp, 0.2]::
## collections of associations || ordering, array and collection methods || code::[0 -> [1, 2, 3], 1 -> [2, 1]]::
## dictionaries: fast lookup || event compatibility || code::(instrument: \sine, freq: 561)::
::
To make it easy to translate between these purposes and representations, there is a uniform set of methods:
TABLE::
##code::asPairs:: || returns an array of key value pairs
##code::asAssociations:: || returns an array of associations
##code::asDict:: || returns an IdentityDictionary.
::
SECTION::Examples
CODE::
// the following all return [\freq, 452, \amp, 0.2]
[\freq, 452, \amp, 0.2].asPairs
[\freq -> 452, \amp -> 0.2].asPairs
(freq: 452, amp: 0.2).asPairs
// the following all return [\freq -> 452, \amp -> 0.2]
[\freq, 452, \amp, 0.2].asAssociations
[\freq -> 452, \amp -> 0.2].asAssociations
(freq: 452, amp: 0.2).asAssociations
// the following all return (freq: 452, amp: 0.2) or the equivalent IdentityDictionary
[\freq, 452, \amp, 0.2].asDict
[\freq -> 452, \amp -> 0.2].asDict
(freq: 452, amp: 0.2).asDict
::
SECTION::Mapping Parameters
The method code::asDict:: optionally takes a code::mergeFunc:: and a code::class:: argument.
CODE::
// IdentityDictionary[ (a -> 1), (c -> 3), (b -> 2) ]
[\a, 1, \a, 3, \b, 2, \c, 3, \c, 7].asDict;
// IdentityDictionary[ (a -> 4), (c -> 10), (b -> 2) ]
[\a, 1, \a, 3, \b, 2, \c, 3, \c, 7].asDict({ |new, old| new + old })
// Dictionary[ (what -> was), (how -> wie), (and -> und), (this -> das) ]
["this", "das", "and", "und", "what", "was", "how", "wie"].asDict(class: Dictionary)
// Environment[ (a -> 1), (b -> 2) ]
[\a, 1, \b, 2].asDict(class: Environment)
::
The method code::asEvent:: is a shortcut:
CODE::
[\freq, 100, \amp, 0.1].asEvent // ( 'amp': 0.1, 'freq': 100 )
::
The methods code::asAssociations:: and code::asPairs:: optionally take a code::class:: argument.
CODE::
// SortedList[ (a -> 1871), (b -> 1848), (c -> 1789) ]
(c:1789, b:1848, a:1871).asAssociations(SortedList);
// LinkedList[ a, 1871, c, 1789, b, 1848 ]
(c:1789, b:1848, a:1871).asPairs(LinkedList);
::
|