Language support Comparison of programming languages (associative array)
1 language support
1.1 awk
1.2 c
1.3 c#
1.4 c++
1.5 cfml
1.6 cobra
1.7 d
1.8 delphi
1.9 erlang
1.10 f#
1.11 foxpro
1.12 go
1.13 haskell
1.14 java
1.15 javascript
1.16 julia
1.17 kornshell 93 (and compliant shells: ksh93, bash4...)
1.18 lisp
1.19 lpc
1.20 lua
1.21 mathematica , wolfram language
1.22 mumps
1.23 objective-c (cocoa/gnustep)
1.24 ocaml
1.25 optimj
1.26 perl
1.27 php
1.28 pike
1.29 postscript
1.30 prolog
1.31 python
1.32 rexx
1.33 ruby
1.34 s-lang
1.35 scala
1.36 smalltalk
1.37 snobol
1.38 standard ml
1.39 tcl
1.40 visual basic
1.41 windows powershell
language support
the following comparison of associative arrays (also mapping , hash , , dictionary ) in various programming languages.
awk
awk has built-in, language-level support associative arrays.
for example:
you can loop through associated array follows:
you can check if element in associative array, , delete elements associative array.
multi-dimensional associative arrays can simulated in standard awk using concatenation , e.g. subsep:
c
there no standard implementation of associative array in c, 3rd party library bsd license available here, archived here, source code available here. posix 1003.1-2001 describes functions hcreate(), hdestroy() , hsearch().
another 3rd party library, uthash, creates associative arrays c structures. structure represents value, , 1 of structure fields acts key.
finally, glib library supports associative arrays, along many other advanced data types , recommended implementation of gnu project.[1]
similar glib, apple s cross-platform core foundation framework provides several basic data types. in particular, there reference counted cfdictionary , cfmutabledictionary.
c#
the dictionary can initialized entries during construction. called object initialization .
a foreach loop can enumerate through entire collection. there no guarantee of order. if order matters programmer choose use sorteddictionary or use .sort linq extension method.
c++
c++ has form of associative array called std::map (see standard template library#containers). 1 create map same information above using c++ following code:
or less efficiently creates temporary std::string values:
with extension of initialization lists in c++11, entries can added during map s construction shown below:
you can iterate through list following code (c++03):
the same task in new c++11:
in c++, std::map class templated allows data types of keys , values different different map instances. given instance of map class keys must of same base type. same must true of values. although std::map typically implemented using self-balancing binary search tree, c++11 defines second map called std::unordered_map algorithmic characteristics of hash table. common vendor extension stl well, called hash_map, being available such implementations sgi , stlport.
cfml
a structure in cfml equivalent associative array:
cobra
initializing empty dictionary , adding items:
dic dictionary<of string, string> = dictionary<of string, string>()
dic.add( sally smart , 555-9999 )
dic.add( john doe , 555-1212 )
dic.add( j. random hacker , 553-1337 )
assert dic[ sally smart ] == 555-9999
alternatively, dictionary can initialized items during construction:
dic = {
sally smart : 555-9999 ,
john doe : 555-1212 ,
j. random hacker : 553-1337
}
the dictionary can enumerated for-loop, there no guaranteed order:
for key, val in dic
print [key] s phone number [val]
d
d offers direct support associative arrays in core language – implemented chaining hash table binary trees. equivalent example be:
keys , values can types, keys in associative array must of same type, , same values.
you can loop through properties , associated values, i.e. follows:
a property can removed follows:
delphi
delphi supports several standard generic containers, including tdictionary<t>:
versions of delphi prior 2009 not offer direct support associative arrays. however, can simulate associative arrays using tstrings class. here s example:
erlang
erlang offers many approaches represent mappings, 2 of common in standard library keylists , dictionaries.
keylists lists of tuples, first element of each tuple key, , second value. functions operating on keylists provided in lists module.
accessing element of keylist can done lists:keyfind/3 function:
dictionaries implemented in dict of standard library. new dictionary created using dict:new/0 function , new key/value pairs stored using dict:store/3 function:
such serial initialization more idiomatically represented in erlang appropriate function:
the dictionary can accessed using dict:find/2 function:
in both cases, erlang term can used key. variations include orddict module, implementing ordered dictionaries, , gb_trees, implementing general balanced trees.
f#
f# constructs maps lists, sequences or arrays of tuples, using functions provided map module. f# represents tuple 2 or more elements separated comma, , list sequence of elements enclosed in square brackets, separated semi-colons.
values can looked via 1 of map object functions, such tryfind. returns option type value of some, successful lookup, or none, unsuccessful one. pattern matching can used extract raw value, or default, result.
in example, sallynumber value contain string 555-9999 .
because f# .net language, has access of features of .net framework, including dictionary objects , hashtable objects used same purpose in both c# , visual basic. these objects may preferred when writing code intended linked other languages on .net framework.
foxpro
visual foxpro implements mapping collection class.
getkey returns 0 if key not found.
see collection in foxpro details.
go
go has built-in, language-level support associative arrays, called maps. map s key type may boolean, numeric, string, array, struct, pointer, interface, or channel type. map type written this: map[keytype]valuetype.
adding elements 1 @ time:
a map literal:
iterating on map:
haskell
the haskell programming language s report provides 1 kind of associative container: list of pairs:
output:
just 555-1212
note lookup function returns maybe value, nothing if not found, or result when found.
ghc, commonly used implementation of haskell, provides 2 more types of associative containers. other implementations might provide these.
one polymorphic functional maps (represented immutable balanced binary trees):
output:
just 555-1212
a specialized version integer keys exists data.intmap.
finally, polymorphic hash table:
output:
just 555-1212
lists of pairs , functional maps both provide purely functional interface, more idiomatic in haskell. in contrast, hash tables provide imperative interface in io monad.
java
in java associative arrays implemented maps ; part of java collections framework. since j2se 5.0 , introduction of generics java, collections can have type specified; example, associative array mapping strings strings might specified follows:
the method used access key; example, value of expression phonebook.get( sally smart ) 555-9999 .
this code above uses hash map store associative array, calling constructor of hashmap class; however, since code uses methods common interface map, 1 use self-balancing binary tree calling constructor of treemap class (which implements subinterface sortedmap), without changing definition of phonebook variable or rest of code, or use number of other underlying data structures implement map interface.
the hash function in java, used hashmap , hashset, provided method object.hashcode(). since every class in java inherits object, every object has hash function. class can override default implementation of hashcode() provide custom hash function based on properties of object.
the object class contains method equals(object) tests object equality object. hashed data structures in java rely on objects maintaining following contract between hashcode() , equals() methods:
for 2 objects , b,
in order maintain contract, class overrides equals() must override hashcode(), , maybe vice versa, hashcode() based on same properties (or subset of properties) equals().
a further contract hashed data structures has object results of hashcode() , equals() methods not change once object has been inserted map. reason, practice base hash function on immutable properties of object.
analogously, treemap, , other sorted data structures, requires ordering defined on data type. either data type must have defined own ordering, implementing comparable interface; or custom comparator must provided @ time map constructed. hashmap above, relative ordering of keys in treemap should not change once have been inserted map.
javascript
javascript (and standardized version: ecmascript) prototype-based object-oriented language. in javascript object mapping property names values—that is, associative array 1 caveat: since property names strings, string , (coerced) integer keys allowed. other difference, objects include 1 feature unrelated associative arrays: prototype link object inherit from. doing lookup property forward lookup prototype if object not define property itself.
an object literal written { property1 : value1, property2 : value2, ... }. example:
if property name valid identifier, quotes can omitted, e.g.:
lookup written using property access notation, either square brackets, works, or dot notation, works identifier keys:
you can loop through enumerable properties , associated values follows:
a property can removed follows:
as mentioned before, properties strings. however, since every native object , primitive can implicitly converted string, can do:
any object, including built-in objects such array, can dynamically extended new properties. example:
in modern javascript s considered bad form use array type associative array. consensus object type best purpose. reasoning behind if array extended via prototype , object kept pristine, for(in) loops work expected on associative arrays . issue has been drawn focus popularity of javascript frameworks make heavy , indiscriminate use of prototype extend javascript s inbuilt types.
see javascript array , object prototype awareness day more information on issue.
julia
declare dictionary:
access element:
phonebook[ sally smart ]
add element:
phonebook[ new contact ] = 555-2222
delete element:
delete!(phonebook, sally smart )
get keys , values iterables:
keys(phonebook)
values(phonebook)
kornshell 93 (and compliant shells: ksh93, bash4...)
definition:
dereference:
lisp
lisp conceived list processing language, , 1 of important data types linked list, can treated association list ( alist ).
the syntax (x . y) used indicate consed pair. keys , values need not same type within alist. lisp , scheme provide operators such assoc manipulate alists in ways similar associative arrays.
because of linear nature, alists used relatively small sets of data. common lisp supports hash table data type, , scheme implemented in srfi 69. hash tables have greater overhead alists, provide faster access when there many elements.
it easy construct composite abstract data types in lisp, using structures and/or object-oriented programming features, in conjunction lists, arrays, , hash tables.
lpc
lpc implements associative arrays fundamental type known either map or mapping, depending on driver. keys , values can of type. mapping literal written ([ key_1 : value_1, key_2 : value_2 ]). procedural use looks like:
mappings accessed reading using indexing operator in same way writing, shown above. phone_book[ sally smart ] return string 555-9999 , , phone_book[ john smith ] return 0. testing presence done using function member(), e.g. if(member(phone_book, john smith )) write( john smith listed.\n );
deletion accomplished using function called either m_delete() or map_delete(), depending on driver, used like: m_delete(phone_book, sally smart );
lpc drivers of amylaar family implement multivalued mappings using secondary, numeric index. (drivers of mudos family not support multivalued mappings.) example syntax:
lpc drivers modern enough support foreach() construct allow iteration on mapping types using it.
lua
in lua, table fundamental type can used either array (numerical index, fast) or associative array. keys , values can of type, except nil. following focuses on non-numerical indexes.
a table literal written { value, key = value, [index] = value, [ non id string ] = value }. example:
if key valid identifier (not keyword), quotes can omitted. case sensitive.
lookup written using either square brackets, works, or dot notation, works identifier keys:
you can loop through keys , associated values iterators or loops:
an entry can removed setting nil:
likewise, can overwrite values or add them:
mathematica , wolfram language
mathematica uses association expression represent associative arrays.
to access
if keys strings, key keyword not necessary, so:
to list keys , values
keys[phonebook]
values[phonebook]
mumps
in mumps every array associative array. built-in, language-level, direct support associative arrays applies private, process-specific arrays stored in memory called locals permanent, shared arrays stored on disk available concurrently multiple jobs. name globals preceded circumflex ^ distinguish local variable names.
set ^phonebook( sally smart )= 555-9999 ;; storing permanent data
set phonebook( john doe )= 555-1212 ;; storing temporary data
set phonebook( j. random hacker )= 553-1337 ;;storing temporary data
merge ^phonebook=phonebook ;;copying temporary data permanent data
to access value of element, requires using name subscript:
write phone number : ,^phonebook( sally smart ),!
you can loop through associated array follows:
set name=
for s name=$order(^phonebook(name)) quit:name= write name, phone number : ,^phonebook(name),!
objective-c (cocoa/gnustep)
cocoa (api) , gnustep handle associative arrays using nsmutabledictionary (a mutable version of nsdictionary) class cluster. class allows assignments between 2 objects made. copy of key object made before inserted nsmutabledictionary, therefore keys must conform nscopying protocol. when being inserted dictionary, value object receives retain message increase reference count. value object receive release message when deleted dictionary (both explicitly or adding dictionary different object same key).
to access assigned objects command may used:
all keys or values can enumerated using nsenumerator
on mac os x 10.5+ , iphone os, dictionary keys can enumerated more concisely using nsfastenumeration construct:
what more practical, structured data graphs may created using cocoa, nsdictionary (nsmutabledictionary). can illustrated compact example:
and relevant fields can accessed using key paths:
ocaml
the ocaml programming language provides 3 different associative containers. simplest list of pairs:
the second polymorphic hash table:
the code above uses ocaml s default hash function hashtbl.hash, defined automatically types. if wanted use own hash function, can use functor interface hashtbl.make create module, map below.
finally, functional maps (represented immutable balanced binary trees):
note in order use map, have provide functor map.make module defines key type , comparison function. third-party library extlib provides polymorphic version of functional maps, called pmap, provide comparison function when creating map.
lists of pairs , functional maps both provide purely functional interface. in contrast, hash tables provide imperative interface. many operations, hash tables faster lists of pairs , functional maps.
optimj
the optimj programming language extension of java 5. java, optimj provides maps. but, optimj provides true associative arrays: java arrays indexed 0-based integers; associative arrays indexed collection of keys.
of course, possible define multi-dimensional arrays, mix java array , associative arrays, mix maps , associative arrays.
perl
perl has built-in, language-level support associative arrays. modern perl vernacular refers associative arrays hashes; term associative array found in older documentation, considered archaic. perl hashes flat: keys strings , values scalars. however, values may references arrays or other hashes, , standard perl module tie::refhash enables hashes used reference keys.
a hash variable marked % sigil, distinguish scalar, array , other data types. hash literal key-value list, preferred form using perl s => token, semantically identical comma , makes key-value association clearer:
accessing hash element uses syntax $hash_name{$key} – key surrounded curly braces , hash name prefixed $, indicating hash element scalar value, though part of hash. value of $phone_book{ john doe } 555-1212 . % sigil used when referring hash whole, such when asking keys %phone_book.
the list of keys , values can extracted using built-in functions keys , values, respectively. so, example, print keys of hash:
one can iterate through (key, value) pairs using each function:
a hash reference, scalar value points hash, specified in literal form using curly braces delimiters, syntax otherwise similar specifying hash literal:
values in hash reference accessed using dereferencing operator:
when hash contained in hash reference needs referred whole, keys function, syntax follows:
php
php s built-in array type in reality associative array. when using numerical indexes, php internally stores associative array. why 1 in php can have non-consecutive numerically indexed arrays. keys have integer or string (floating point numbers truncated integer), while values can of arbitrary types, including other arrays , objects. arrays heterogeneous; single array can have keys of different types. php s associative arrays can used represent trees, lists, stacks, queues , other common data structures not built php.
an associative array can declared using following syntax:
php can loop through associative array follows:
php has extensive set of functions operate on arrays.
if want associative array can use objects keys instead of strings , integers, can use splobjectstorage class standard php library (spl).
pike
pike has built-in support associative arrays, referred mappings. mappings created follows:
accessing , testing presence in mappings done using indexing operator. phonebook[ sally smart ] return string 555-9999 , , phonebook[ john smith ] return 0.
iterating through mapping can done using either foreach:
or using iterator object:
elements of mapping can removed using m_delete, returns value of removed index:
postscript
in postscript, associative arrays called dictionaries. in level 1 postscript must created explicitly, level 2 introduced direct declaration using double-brace syntax:
dictionaries can accessed directly using or implicitly placing dictionary on dictionary stack using begin:
dictionary contents can iterated through using forall, though not in particular order:
may output:
dictionaries can augmented (up defined size in level 1) or altered using put, , entries can removed using undef:
prolog
some versions of prolog include dicts .
python
in python, associative arrays called dictionaries. dictionary literals marked curly braces:
to access entry in python use array indexing operator. example,
an example loop iterating through keys of dictionary:
iterating through (key, value) tuples:
dictionary keys can individually deleted using del statement. corresponding value can returned before key-value pair deleted using pop method of dict types:
python 2.7 , 3.x supports dictionary comprehensions, compact syntax generating dictionary iterator:
rexx
in rexx, associative arrays called stem variables or compound variables.
stem variables numeric keys typically start @ 1 , go there. 0 key stem variable used (by convention) count of items in whole stem.
rexx has no easy way of automatically accessing keys stem variable , typically keys stored in separate associative array numeric keys.
ruby
in ruby hash used follows:
ruby supports hash looping , iteration following syntax:
ruby supports many other useful operations on hashes, such merging hashes, selecting or rejecting elements meet criteria, inverting (swapping keys , values), , flattening hash array.
s-lang
s-lang has associative array type.
for example:
you can loop through associated array in number of ways. here one
to print sorted-list, better take advantage of s-lang s strong support standard arrays:
scala
scala provides immutable map class part of scala.collection framework:
scala s type inference work out map[string, string]. access array:
this returns option type, scala s equivalent of maybe monad in haskell.
smalltalk
in smalltalk dictionary used:
to access entry message #at: sent dictionary object.
gives
dictionary hashes/compares based on equality , holds strong references both key , value. variants exist hash/compare on identity (identitydictionary) or keep weak references (weakkeydictionary / weakvaluedictionary). because every object implements #hash, object can used key (and of course value).
snobol
snobol 1 of first (if not first) programming languages use associative arrays. associative arrays in snobol called tables.
standard ml
the sml 97 standard of standard ml programming language not provide associative containers. however, various implementations of standard ml provide associative containers.
the library of popular standard ml of new jersey implementation provides signature (somewhat interface ), ord_map, defines common interface ordered functional (immutable) associative arrays. there several general functors, binarymapfn, listmapfn, redblackmapfn, , splaymapfn, allow create corresponding type of ordered map (the types self-balancing binary search tree, sorted association list, red-black tree, , splay tree, respectively) using user-provided structure describe key type , comparator. functor returns structure follows ord_map interface. in addition, there 2 pre-defined modules associative arrays integer keys: intbinarymap , intlistmap.
sml/nj provides polymorphic hash table:
monomorphic hash tables supported using hashtablefn functor.
another standard ml implementation, moscow ml, provides associative containers. first, provides polymorphic hash tables in polyhash structure. also, functional maps sml/nj library above available binarymap, splaymap, , intmap structures.
tcl
there 2 tcl facilities support associative array semantics. array collection of variables. dict full implementation of associative arrays.
dict
to item:
to iterate through dict:
array
if there literal space character in variable name, must grouped using either curly brackets (no substitution performed) or double quotes (substitution performed).
alternatively, several array elements can set in single command providing mappings list (words containing whitespace braced):
to access 1 array entry , put on standard output
the result here
to retrieve entire array dictionary:
the result can (order of keys unspecified, not because dictionary unordered, because array is):
visual basic
there no standard implementation common dialects. visual basic can use dictionary class microsoft scripting runtime (which shipped visual basic 6):
visual basic .net relies on collection classes provided .net framework:
windows powershell
unlike many other command line interpreters, powershell has built-in, language-level support defining associative arrays.
for example:
like in javascript, if property name valid identifier, quotes can omitted, e.g.:
entries can separated either semicolon or newline, e.g.:
keys , values can .net object type, e.g.:
it possible create empty associative array , add single entries or other associative arrays later on.
new entries can added using array index operator, property operator or add() method of underlying .net object:
to dereference assigned objects array index operator, property operator or parameterized property item() of .net object can used:
you can loop through associative array follows:
an entry can removed using remove() method of underlying .net object:
hash tables can added, e.g.:
Comments
Post a Comment