Collections: Difference between revisions
Content added Content deleted
(→{{header|Diego}}: Added Diego entry) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 26: | Line 26: | ||
In this example, we're creating a collection of strings associated with the vector table of the 68000's CPU. It's not too important what this data represents, it's more to showcase an actual application of the concept of a collection of pointers being more convenient than a collection of actual strings, so don't worry if you don't understand what these strings mean. |
In this example, we're creating a collection of strings associated with the vector table of the 68000's CPU. It's not too important what this data represents, it's more to showcase an actual application of the concept of a collection of pointers being more convenient than a collection of actual strings, so don't worry if you don't understand what these strings mean. |
||
< |
<syntaxhighlight lang="68000devpac"> dc.l TrapString_Bus |
||
dc.l TrapString_Addr |
dc.l TrapString_Addr |
||
dc.l TrapString_Illegal |
dc.l TrapString_Illegal |
||
Line 58: | Line 58: | ||
TrapString_trace: |
TrapString_trace: |
||
dc.b "Tracing",255 |
dc.b "Tracing",255 |
||
even</ |
even</syntaxhighlight> |
||
As mentioned earlier, 68000 Assembly doesn't know (or care) what types of data are stored in an array or collection, although if you try to read from an odd memory address at word or long length your CPU will suffer an alignment fault. The CPU doesn't care what types of data are actually stored in an array. It's the programmer's job to tell the CPU what the data actually means. |
As mentioned earlier, 68000 Assembly doesn't know (or care) what types of data are stored in an array or collection, although if you try to read from an odd memory address at word or long length your CPU will suffer an alignment fault. The CPU doesn't care what types of data are actually stored in an array. It's the programmer's job to tell the CPU what the data actually means. |
||
Line 64: | Line 64: | ||
=={{header|ABAP}}== |
=={{header|ABAP}}== |
||
<syntaxhighlight lang="abap"> |
|||
<lang ABAP> |
|||
REPORT z_test_rosetta_collection. |
REPORT z_test_rosetta_collection. |
||
Line 83: | Line 83: | ||
START-OF-SELECTION. |
START-OF-SELECTION. |
||
NEW lcl_collection( )->start( ). |
NEW lcl_collection( )->start( ). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
Line 94: | Line 94: | ||
Anonymous arrays have no type associated with them that is accessible to the programmer. This means that anonymous arrays cannot be compared in the aggregate to other arrays (even those with the same index structure and contained type) or passed as a parameter to a subprogram. For these reasons, anonymous arrays are best used as singletons and global constants. |
Anonymous arrays have no type associated with them that is accessible to the programmer. This means that anonymous arrays cannot be compared in the aggregate to other arrays (even those with the same index structure and contained type) or passed as a parameter to a subprogram. For these reasons, anonymous arrays are best used as singletons and global constants. |
||
< |
<syntaxhighlight lang="ada">procedure Array_Collection is |
||
A : array (-3 .. -1) of Integer := (1, 2, 3); |
A : array (-3 .. -1) of Integer := (1, 2, 3); |
||
Line 104: | Line 104: | ||
A (-1) := 1; |
A (-1) := 1; |
||
end Array_Collection;</ |
end Array_Collection;</syntaxhighlight> |
||
===array types=== |
===array types=== |
||
Because of the limitations of anonymous arrays noted above, arrays are more typically defined in Ada as array types, as in the example below. |
Because of the limitations of anonymous arrays noted above, arrays are more typically defined in Ada as array types, as in the example below. |
||
< |
<syntaxhighlight lang="ada">procedure Array_Collection is |
||
type Array_Type is array (1 .. 3) of Integer; |
type Array_Type is array (1 .. 3) of Integer; |
||
Line 120: | Line 120: | ||
A (3) := 1; |
A (3) := 1; |
||
end Array_Collection;</ |
end Array_Collection;</syntaxhighlight> |
||
===unconstrained arrays=== |
===unconstrained arrays=== |
||
Dynamic arrays can be created through the use of pointers to unconstrained arrays. While an unconstrained array's index type is defined, it does not have a pre-defined range of indices - they are specified at the time of declaration or, as would be the case in a dynamic array, at the time the memory for the array is allocated. The creation of a dynamic array is not shown here, but below is an example declaration of an unconstrained array in Ada. |
Dynamic arrays can be created through the use of pointers to unconstrained arrays. While an unconstrained array's index type is defined, it does not have a pre-defined range of indices - they are specified at the time of declaration or, as would be the case in a dynamic array, at the time the memory for the array is allocated. The creation of a dynamic array is not shown here, but below is an example declaration of an unconstrained array in Ada. |
||
< |
<syntaxhighlight lang="ada">procedure Array_Collection is |
||
type Array_Type is array (positive range <>) of Integer; -- may be indexed with any positive |
type Array_Type is array (positive range <>) of Integer; -- may be indexed with any positive |
||
Line 137: | Line 137: | ||
A (3) := 1; |
A (3) := 1; |
||
end Array_Collection;</ |
end Array_Collection;</syntaxhighlight> |
||
===doubly linked lists=== |
===doubly linked lists=== |
||
Line 144: | Line 144: | ||
{{libheader|Ada.Containers.Doubly_Linked_Lists}} |
{{libheader|Ada.Containers.Doubly_Linked_Lists}} |
||
< |
<syntaxhighlight lang="ada">with Ada.Containers.Doubly_Linked_Lists; |
||
use Ada.Containers; |
use Ada.Containers; |
||
Line 160: | Line 160: | ||
DL_List.Append (3); |
DL_List.Append (3); |
||
end Doubly_Linked_List;</ |
end Doubly_Linked_List;</syntaxhighlight> |
||
===vectors=== |
===vectors=== |
||
Line 167: | Line 167: | ||
{{libheader|Ada.Containers.Vectors}} |
{{libheader|Ada.Containers.Vectors}} |
||
< |
<syntaxhighlight lang="ada">with Ada.Containers.Vectors; |
||
use Ada.Containers; |
use Ada.Containers; |
||
Line 183: | Line 183: | ||
V.Append (3); |
V.Append (3); |
||
end Vector_Example;</ |
end Vector_Example;</syntaxhighlight> |
||
=={{header|Aime}}== |
=={{header|Aime}}== |
||
Line 190: | Line 190: | ||
===Lists=== |
===Lists=== |
||
Declaring a list: |
Declaring a list: |
||
<lang |
<syntaxhighlight lang="aime">list l;</syntaxhighlight> |
||
Adding values to it: |
Adding values to it: |
||
< |
<syntaxhighlight lang="aime">l_p_integer(l, 0, 7); |
||
l_push(l, "a string"); |
l_push(l, "a string"); |
||
l_append(l, 2.5);</ |
l_append(l, 2.5);</syntaxhighlight> |
||
Retrieving values from a list: |
Retrieving values from a list: |
||
< |
<syntaxhighlight lang="aime">l_query(l, 2) |
||
l_head(l) |
l_head(l) |
||
l_q_text(l, 1) |
l_q_text(l, 1) |
||
l[3]</ |
l[3]</syntaxhighlight> |
||
===Records=== |
===Records=== |
||
Declaring a record: |
Declaring a record: |
||
<lang |
<syntaxhighlight lang="aime">record r;</syntaxhighlight> |
||
Adding values to it: |
Adding values to it: |
||
< |
<syntaxhighlight lang="aime">r_p_integer(r, "key1", 7); |
||
r_put(r, "key2", "a string"); |
r_put(r, "key2", "a string"); |
||
r["key3"] = .25;</ |
r["key3"] = .25;</syntaxhighlight> |
||
Retrieving values from a record: |
Retrieving values from a record: |
||
< |
<syntaxhighlight lang="aime">r_query(r, "key1") |
||
r_tail(r) |
r_tail(r) |
||
r["key2"]</ |
r["key2"]</syntaxhighlight> |
||
=={{header|ALGOL 68}}== |
=={{header|ALGOL 68}}== |
||
Arrays are the closest thing to collections available as standard in Algol 68. Collections could be implemented using STRUCTs but there are none as standard. Some examples of arrays: |
Arrays are the closest thing to collections available as standard in Algol 68. Collections could be implemented using STRUCTs but there are none as standard. Some examples of arrays: |
||
< |
<syntaxhighlight lang="algol68"># create a constant array of integers and set its values # |
||
[]INT constant array = ( 1, 2, 3, 4 ); |
[]INT constant array = ( 1, 2, 3, 4 ); |
||
# create an array of integers that can be changed, note the size mst be specified # |
# create an array of integers that can be changed, note the size mst be specified # |
||
Line 236: | Line 236: | ||
# replace it with a new array of 5 elements # |
# replace it with a new array of 5 elements # |
||
fa := LOC[ -2 : 2 ]INT; |
fa := LOC[ -2 : 2 ]INT; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Apex}}== |
=={{header|Apex}}== |
||
Line 242: | Line 242: | ||
A list is an ordered collection of elements that are distinguished by their indices |
A list is an ordered collection of elements that are distinguished by their indices |
||
Creating Lists |
Creating Lists |
||
< |
<syntaxhighlight lang="apex"> |
||
// Create an empty list of String |
// Create an empty list of String |
||
List<String> my_list = new List<String>(); |
List<String> my_list = new List<String>(); |
||
// Create a nested list |
// Create a nested list |
||
List<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>(); |
List<List<Set<Integer>>> my_list_2 = new List<List<Set<Integer>>>(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Access elements in a list |
Access elements in a list |
||
< |
<syntaxhighlight lang="apex"> |
||
List<Integer> myList = new List<Integer>(); // Define a new list |
List<Integer> myList = new List<Integer>(); // Define a new list |
||
myList.add(47); // Adds a second element of value 47 to the end |
myList.add(47); // Adds a second element of value 47 to the end |
||
Line 256: | Line 256: | ||
myList.set(0, 1); // Adds the integer 1 to the list at index 0 |
myList.set(0, 1); // Adds the integer 1 to the list at index 0 |
||
myList.clear(); // Removes all elements from the list |
myList.clear(); // Removes all elements from the list |
||
</syntaxhighlight> |
|||
</lang> |
|||
Using Array Notation for One-dimensional list |
Using Array Notation for One-dimensional list |
||
< |
<syntaxhighlight lang="apex"> |
||
String[] colors = new List<String>(); |
String[] colors = new List<String>(); |
||
List<String> colors = new String[1]; |
List<String> colors = new String[1]; |
||
colors[0] = 'Green'; |
colors[0] = 'Green'; |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Sets=== |
===Sets=== |
||
A set is an unordered collection of elements that do not contain any duplicates. |
A set is an unordered collection of elements that do not contain any duplicates. |
||
Defining a set: |
Defining a set: |
||
< |
<syntaxhighlight lang="apex"> |
||
Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements |
Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements |
||
Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the |
Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the |
||
// elements of the set created in the previous step |
// elements of the set created in the previous step |
||
</syntaxhighlight> |
|||
</lang> |
|||
Access elements in a set: |
Access elements in a set: |
||
< |
<syntaxhighlight lang="apex"> |
||
Set<Integer> s = new Set<Integer>(); // Define a new set |
Set<Integer> s = new Set<Integer>(); // Define a new set |
||
s.add(1); // Add an element to the set |
s.add(1); // Add an element to the set |
||
System.assert(s.contains(1)); // Assert that the set contains an element |
System.assert(s.contains(1)); // Assert that the set contains an element |
||
s.remove(1); // Remove the element from the set |
s.remove(1); // Remove the element from the set |
||
</syntaxhighlight> |
|||
</lang> |
|||
Note the following limitations on sets: |
Note the following limitations on sets: |
||
* Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations (for example, HashSet or TreeSet). Apex uses a hash structure for all sets. |
* Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations (for example, HashSet or TreeSet). Apex uses a hash structure for all sets. |
||
Line 287: | Line 287: | ||
A map is a collection of key-value pairs where each unique key maps to a single value |
A map is a collection of key-value pairs where each unique key maps to a single value |
||
Declaring a map: |
Declaring a map: |
||
< |
<syntaxhighlight lang="apex"> |
||
Map<String, String> country_currencies = new Map<String, String>(); |
Map<String, String> country_currencies = new Map<String, String>(); |
||
Map<ID, Set<String>> m = new Map<ID, Set<String>>(); |
Map<ID, Set<String>> m = new Map<ID, Set<String>>(); |
||
Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' => 'd'.toUpperCase()}; |
Map<String, String> MyStrings = new Map<String, String>{'a' => 'b', 'c' => 'd'.toUpperCase()}; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Accessing a Map: |
Accessing a Map: |
||
< |
<syntaxhighlight lang="apex"> |
||
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map |
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map |
||
m.put(1, 'First entry'); // Insert a new key-value pair in the map |
m.put(1, 'First entry'); // Insert a new key-value pair in the map |
||
Line 301: | Line 301: | ||
System.assertEquals('Second entry', value); |
System.assertEquals('Second entry', value); |
||
Set<Integer> s = m.keySet(); // Return a set that contains all of the keys in the map |
Set<Integer> s = m.keySet(); // Return a set that contains all of the keys in the map |
||
</syntaxhighlight> |
|||
</lang> |
|||
Map Considerations: |
Map Considerations: |
||
* Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations (for example, HashMap or TreeMap). Apex uses a hash structure for all maps. |
* Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a map in their declarations (for example, HashMap or TreeMap). Apex uses a hash structure for all maps. |
||
Line 316: | Line 316: | ||
===Array=== |
===Array=== |
||
< |
<syntaxhighlight lang="rebol">; initialize array |
||
arr: ["one" 2 "three" "four"] |
arr: ["one" 2 "three" "four"] |
||
Line 323: | Line 323: | ||
; print it |
; print it |
||
print arr</ |
print arr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 331: | Line 331: | ||
===Dictionary=== |
===Dictionary=== |
||
< |
<syntaxhighlight lang="rebol">; initialize dictionary |
||
dict: #[ |
dict: #[ |
||
name: "john" |
name: "john" |
||
Line 343: | Line 343: | ||
; print it |
; print it |
||
print dict</ |
print dict</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 353: | Line 353: | ||
{{works with|AutoHotkey_L}} |
{{works with|AutoHotkey_L}} |
||
[http://l.autohotkey.net/docs/Objects.htm Documentation] |
[http://l.autohotkey.net/docs/Objects.htm Documentation] |
||
< |
<syntaxhighlight lang="autohotkey">myCol := Object() |
||
mycol.mykey := "my value!" |
mycol.mykey := "my value!" |
||
mycol["mykey"] := "new val!" |
mycol["mykey"] := "new val!" |
||
MsgBox % mycol.mykey ; new val</ |
MsgBox % mycol.mykey ; new val</syntaxhighlight> |
||
===Pseudo-arrays=== |
===Pseudo-arrays=== |
||
Documentation: http://www.autohotkey.com/docs/misc/Arrays.htm |
Documentation: http://www.autohotkey.com/docs/misc/Arrays.htm |
||
< |
<syntaxhighlight lang="autohotkey">Loop 3 |
||
array%A_Index% := A_Index * 9 |
array%A_Index% := A_Index * 9 |
||
MsgBox % array1 " " array2 " " array3 ; 9 18 27</ |
MsgBox % array1 " " array2 " " array3 ; 9 18 27</syntaxhighlight> |
||
===Structs=== |
===Structs=== |
||
Structs are not natively supported in AutoHotkey, however they are often required in DllCalls to C++ Dlls. |
Structs are not natively supported in AutoHotkey, however they are often required in DllCalls to C++ Dlls. |
||
This shows how to retrieve values from a RECT structure in AutoHotkey (from the DllCall documentation at http://www.autohotkey.com/docs/commands/DllCall.htm) |
This shows how to retrieve values from a RECT structure in AutoHotkey (from the DllCall documentation at http://www.autohotkey.com/docs/commands/DllCall.htm) |
||
< |
<syntaxhighlight lang="autohotkey">VarSetCapacity(Rect, 16) ; A RECT is a struct consisting of four 32-bit integers (i.e. 4*4=16). |
||
DllCall("GetWindowRect", UInt, WinExist(), UInt, &Rect) ; WinExist() returns an HWND. |
DllCall("GetWindowRect", UInt, WinExist(), UInt, &Rect) ; WinExist() returns an HWND. |
||
MsgBox % "Left " . NumGet(Rect, 0, true) . " Top " . NumGet(Rect, 4, true) |
MsgBox % "Left " . NumGet(Rect, 0, true) . " Top " . NumGet(Rect, 4, true) |
||
. " Right " . NumGet(Rect, 8, true) . " Bottom " . NumGet(Rect, 12, true)</ |
. " Right " . NumGet(Rect, 8, true) . " Bottom " . NumGet(Rect, 12, true)</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
In awk, the closest thing to collections would be arrays. They are created when needed at assignment |
In awk, the closest thing to collections would be arrays. They are created when needed at assignment |
||
< |
<syntaxhighlight lang="awk">a[0]="hello"</syntaxhighlight> |
||
or by splitting a string |
or by splitting a string |
||
< |
<syntaxhighlight lang="awk">split("one two three",a)</syntaxhighlight> |
||
Single elements are accessible with the bracket notation, like in C: |
Single elements are accessible with the bracket notation, like in C: |
||
<lang |
<syntaxhighlight lang="awk">print a[0]</syntaxhighlight> |
||
One can iterate over the elements of an array: |
One can iterate over the elements of an array: |
||
< |
<syntaxhighlight lang="awk">for(i in a) print i":"a[i]</syntaxhighlight> |
||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
< |
<syntaxhighlight lang="axe">1→{L₁} |
||
2→{L₁+1} |
2→{L₁+1} |
||
3→{L₁+2} |
3→{L₁+2} |
||
Line 389: | Line 389: | ||
Disp {L₁+1}►Dec,i |
Disp {L₁+1}►Dec,i |
||
Disp {L₁+2}►Dec,i |
Disp {L₁+2}►Dec,i |
||
Disp {L₁+3}►Dec,i</ |
Disp {L₁+3}►Dec,i</syntaxhighlight> |
||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
===Arrays=== |
===Arrays=== |
||
In BBC BASIC the only native type of 'collection' is the array; the index starts at zero and the subscript specified in the DIM is the highest value of the index. Hence in this example an array with two elements is defined: |
In BBC BASIC the only native type of 'collection' is the array; the index starts at zero and the subscript specified in the DIM is the highest value of the index. Hence in this example an array with two elements is defined: |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM text$(1) |
||
text$(0) = "Hello " |
text$(0) = "Hello " |
||
text$(1) = "world!"</ |
text$(1) = "world!"</syntaxhighlight> |
||
===Arrays of structures=== |
===Arrays of structures=== |
||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
When the objects in the collection are not simple scalar types an array of structures may be used: |
When the objects in the collection are not simple scalar types an array of structures may be used: |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM collection{(1) name$, year%} |
||
collection{(0)}.name$ = "Richard" |
collection{(0)}.name$ = "Richard" |
||
collection{(0)}.year% = 1952 |
collection{(0)}.year% = 1952 |
||
collection{(1)}.name$ = "Sue" |
collection{(1)}.name$ = "Sue" |
||
collection{(1)}.year% = 1950</ |
collection{(1)}.year% = 1950</syntaxhighlight> |
||
===Linked lists=== |
===Linked lists=== |
||
Although not a native language feature, other types of collections such as linked lists may be constructed: |
Although not a native language feature, other types of collections such as linked lists may be constructed: |
||
< |
<syntaxhighlight lang="bbcbasic"> DIM node{name$, year%, link%} |
||
list% = 0 |
list% = 0 |
||
PROCadd(list%, node{}, "Richard", 1952) |
PROCadd(list%, node{}, "Richard", 1952) |
||
Line 430: | Line 430: | ||
l% = c.link% |
l% = c.link% |
||
ENDWHILE |
ENDWHILE |
||
ENDPROC</ |
ENDPROC</syntaxhighlight> |
||
=={{header|bc}}== |
=={{header|bc}}== |
||
Line 440: | Line 440: | ||
One thing in C language proper that can be said to be a collection is array type. |
One thing in C language proper that can be said to be a collection is array type. |
||
An array has a length known at compile time. |
An array has a length known at compile time. |
||
< |
<syntaxhighlight lang="c">#define cSize( a ) ( sizeof(a)/sizeof(a[0]) ) /* a.size() */ |
||
int ar[10]; /* Collection<Integer> ar = new ArrayList<Integer>(10); */ |
int ar[10]; /* Collection<Integer> ar = new ArrayList<Integer>(10); */ |
||
ar[0] = 1; /* ar.set(0, 1); */ |
ar[0] = 1; /* ar.set(0, 1); */ |
||
Line 450: | Line 450: | ||
p++) { /* pValue=p.next() ) { */ |
p++) { /* pValue=p.next() ) { */ |
||
printf("%d\n",*p); /* System.out.println(pValue); */ |
printf("%d\n",*p); /* System.out.println(pValue); */ |
||
} /* } */</ |
} /* } */</syntaxhighlight> |
||
Please note that c built-in pointer-arithmetic support which helps this logic. An integer may be 4 bytes, and a char 1 byte: the plus operator (+) is overloaded to multiply a incement by 4 for integer pointers and by 1 for char pointers (etc). |
Please note that c built-in pointer-arithmetic support which helps this logic. An integer may be 4 bytes, and a char 1 byte: the plus operator (+) is overloaded to multiply a incement by 4 for integer pointers and by 1 for char pointers (etc). |
||
Another construct which can be seen as a collection is a malloced array. The size of a malloced array is not known at compile time. |
Another construct which can be seen as a collection is a malloced array. The size of a malloced array is not known at compile time. |
||
<syntaxhighlight lang="c"> |
|||
<lang c> |
|||
int* ar; /* Collection<Integer> ar; */ |
int* ar; /* Collection<Integer> ar; */ |
||
int arSize; |
int arSize; |
||
Line 466: | Line 466: | ||
p++) { /* pValue=p.next() ) { */ |
p++) { /* pValue=p.next() ) { */ |
||
printf("%d\n",*p); /* System.out.println(pValue); */ |
printf("%d\n",*p); /* System.out.println(pValue); */ |
||
} /* } */</ |
} /* } */</syntaxhighlight> |
||
A string is another C language construct (when looked at with its standard libraries) that behaves like a collection. |
A string is another C language construct (when looked at with its standard libraries) that behaves like a collection. |
||
Line 476: | Line 476: | ||
===Arrays=== |
===Arrays=== |
||
< |
<syntaxhighlight lang="csharp"> |
||
// Creates and initializes a new integer Array |
// Creates and initializes a new integer Array |
||
int[] intArray = new int[5] { 1, 2, 3, 4, 5 }; |
int[] intArray = new int[5] { 1, 2, 3, 4, 5 }; |
||
Line 487: | Line 487: | ||
string[] stringArr = new string[5]; |
string[] stringArr = new string[5]; |
||
stringArr[0] = "string"; |
stringArr[0] = "string"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
===ArrayList and List=== |
===ArrayList and List=== |
||
The size of ArrayList is dynamically increased as required. ArrayLists are zero-based. |
The size of ArrayList is dynamically increased as required. ArrayLists are zero-based. |
||
< |
<syntaxhighlight lang="csharp"> |
||
//Create and initialize ArrayList |
//Create and initialize ArrayList |
||
ArrayList myAl = new ArrayList { "Hello", "World", "!" }; |
ArrayList myAl = new ArrayList { "Hello", "World", "!" }; |
||
Line 501: | Line 501: | ||
myAL.Add("!"); |
myAL.Add("!"); |
||
</syntaxhighlight> |
|||
</lang> |
|||
The List class is the generic equivalent of the ArrayList class. |
The List class is the generic equivalent of the ArrayList class. |
||
A List is a strongly typed list of objects that can be accessed by index ( zero-based again). |
A List is a strongly typed list of objects that can be accessed by index ( zero-based again). |
||
< |
<syntaxhighlight lang="csharp"> |
||
//Create and initialize List |
//Create and initialize List |
||
List<string> myList = new List<string> { "Hello", "World", "!" }; |
List<string> myList = new List<string> { "Hello", "World", "!" }; |
||
Line 514: | Line 514: | ||
myList2.Add("World"); |
myList2.Add("World"); |
||
myList2.Add("!"); |
myList2.Add("!"); |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Hashtable and Dictionary=== |
===Hashtable and Dictionary=== |
||
Hashtables represent a collection of key/value pairs that are organized based on the hash code of the key. |
Hashtables represent a collection of key/value pairs that are organized based on the hash code of the key. |
||
Keys must be unique. |
Keys must be unique. |
||
< |
<syntaxhighlight lang="csharp"> |
||
//Create an initialize Hashtable |
//Create an initialize Hashtable |
||
Hashtable myHt = new Hashtable() { { "Hello", "World" }, { "Key", "Value" } }; |
Hashtable myHt = new Hashtable() { { "Hello", "World" }, { "Key", "Value" } }; |
||
Line 527: | Line 527: | ||
myHt2.Add("Hello", "World"); |
myHt2.Add("Hello", "World"); |
||
myHt2.Add("Key", "Value"); |
myHt2.Add("Key", "Value"); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Dictionary is a generic class.It represents a collection of key/value pairs. Keys must be unique. |
Dictionary is a generic class.It represents a collection of key/value pairs. Keys must be unique. |
||
< |
<syntaxhighlight lang="csharp"> |
||
//Create an initialize Dictionary |
//Create an initialize Dictionary |
||
Dictionary<string, string> dict = new Dictionary<string, string>() { { "Hello", "World" }, { "Key", "Value" } }; |
Dictionary<string, string> dict = new Dictionary<string, string>() { { "Hello", "World" }, { "Key", "Value" } }; |
||
Line 536: | Line 536: | ||
dict2.Add("Hello", "World"); |
dict2.Add("Hello", "World"); |
||
dict2.Add("Key", "Value"); |
dict2.Add("Key", "Value"); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C++}}== |
=={{header|C++}}== |
||
Line 546: | Line 546: | ||
The simplest collection in C++ is the built-in array. Built-in arrays have a fixed size, and except for POD types (i.e. basically any type you culd also write in C), the members are all initialized at array creation time (if no explicit initialization is done, the default constructr is used). |
The simplest collection in C++ is the built-in array. Built-in arrays have a fixed size, and except for POD types (i.e. basically any type you culd also write in C), the members are all initialized at array creation time (if no explicit initialization is done, the default constructr is used). |
||
< |
<syntaxhighlight lang="cpp">int a[5]; // array of 5 ints (since int is POD, the members are not initialized) |
||
a[0] = 1; // indexes start at 0 |
a[0] = 1; // indexes start at 0 |
||
Line 553: | Line 553: | ||
#include <string> |
#include <string> |
||
std::string strings[4]; // std::string is no POD, therefore all array members are default-initialized |
std::string strings[4]; // std::string is no POD, therefore all array members are default-initialized |
||
// (for std::string this means initialized with empty strings)</ |
// (for std::string this means initialized with empty strings)</syntaxhighlight> |
||
===vector=== |
===vector=== |
||
A vector is basically a resizable array. It is optimized for adding/removing elements on the end, and fast access to elements anywhere. Inserting elements at the beginning or in the middle is possible, but in general inefficient. |
A vector is basically a resizable array. It is optimized for adding/removing elements on the end, and fast access to elements anywhere. Inserting elements at the beginning or in the middle is possible, but in general inefficient. |
||
< |
<syntaxhighlight lang="cpp">#include <vector> |
||
std::vector<int> v; // empty vector |
std::vector<int> v; // empty vector |
||
v.push_back(5); // insert a 5 at the end |
v.push_back(5); // insert a 5 at the end |
||
v.insert(v.begin(), 7); // insert a 7 at the beginning</ |
v.insert(v.begin(), 7); // insert a 7 at the beginning</syntaxhighlight> |
||
===deque=== |
===deque=== |
||
A deque is optimized for appending and removing elements on both ends ofd the array. Accessing random elements is still efficient, but slightly less than with vector. |
A deque is optimized for appending and removing elements on both ends ofd the array. Accessing random elements is still efficient, but slightly less than with vector. |
||
< |
<syntaxhighlight lang="cpp">#include <deque> |
||
std::deque<int> d; // empty deque |
std::deque<int> d; // empty deque |
||
d.push_back(5); // insert a 5 at the end |
d.push_back(5); // insert a 5 at the end |
||
d.push_front(7); // insert a 7 at the beginning |
d.push_front(7); // insert a 7 at the beginning |
||
d.insert(v.begin()+1, 6); // insert a 6 in the middle</ |
d.insert(v.begin()+1, 6); // insert a 6 in the middle</syntaxhighlight> |
||
===list=== |
===list=== |
||
A list is optimized for insertion at an arbitrary place (provided you already have an iterator pointing to that place). Element access is efficient only in linear order. |
A list is optimized for insertion at an arbitrary place (provided you already have an iterator pointing to that place). Element access is efficient only in linear order. |
||
< |
<syntaxhighlight lang="cpp">#include <list> |
||
std::list<int> l; // empty list |
std::list<int> l; // empty list |
||
Line 584: | Line 584: | ||
std::list::iterator i = l.begin(); |
std::list::iterator i = l.begin(); |
||
++l; |
++l; |
||
l.insert(i, 6); // insert a 6 in the middle</ |
l.insert(i, 6); // insert a 6 in the middle</syntaxhighlight> |
||
===set=== |
===set=== |
||
A set keeps the inserted elements sorted, and also makes sure that each element occurs only once. Of course, if you want to put something into a set, it must be less-than-comparable, i.e. you must be able to compare which of two objects <tt>a</tt> and <tt>b</tt> is smaller using <tt>a<b</tt> (there's also a way to define sets with an user-defined order, in which case this restriction doesn't apply). |
A set keeps the inserted elements sorted, and also makes sure that each element occurs only once. Of course, if you want to put something into a set, it must be less-than-comparable, i.e. you must be able to compare which of two objects <tt>a</tt> and <tt>b</tt> is smaller using <tt>a<b</tt> (there's also a way to define sets with an user-defined order, in which case this restriction doesn't apply). |
||
< |
<syntaxhighlight lang="cpp">#include <set> |
||
std::set<int> s; // empty set |
std::set<int> s; // empty set |
||
s.insert(5); // insert a 5 |
s.insert(5); // insert a 5 |
||
s.insert(7); // insert a 7 (automatically placed after the 5) |
s.insert(7); // insert a 7 (automatically placed after the 5) |
||
s.insert(5); // try to insert another 5 (will not change the set)</ |
s.insert(5); // try to insert another 5 (will not change the set)</syntaxhighlight> |
||
===multiset=== |
===multiset=== |
||
A multiset is like a set, except the same element may occur multiple times. |
A multiset is like a set, except the same element may occur multiple times. |
||
< |
<syntaxhighlight lang="cpp">#include <multiset> |
||
std::multiset<int> m; // empty multiset |
std::multiset<int> m; // empty multiset |
||
m.insert(5); // insert a 5 |
m.insert(5); // insert a 5 |
||
m.insert(7); // insert a 7 (automatically placed after the 5) |
m.insert(7); // insert a 7 (automatically placed after the 5) |
||
m.insert(5); // insert a second 5 (now m contains two 5s, followed by one 7)</ |
m.insert(5); // insert a second 5 (now m contains two 5s, followed by one 7)</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Line 610: | Line 610: | ||
===Hash maps=== |
===Hash maps=== |
||
< |
<syntaxhighlight lang="clojure">{1 "a", "Q" 10} ; commas are treated as whitespace |
||
(hash-map 1 "a" "Q" 10) ; equivalent to the above |
(hash-map 1 "a" "Q" 10) ; equivalent to the above |
||
(let [my-map {1 "a"}] |
(let [my-map {1 "a"}] |
||
(assoc my-map "Q" 10)) ; "adding" an element</ |
(assoc my-map "Q" 10)) ; "adding" an element</syntaxhighlight> |
||
===Lists=== |
===Lists=== |
||
< |
<syntaxhighlight lang="clojure">'(1 4 7) ; a linked list |
||
(list 1 4 7) |
(list 1 4 7) |
||
(cons 1 (cons 4 '(7)))</ |
(cons 1 (cons 4 '(7)))</syntaxhighlight> |
||
===Vectors=== |
===Vectors=== |
||
< |
<syntaxhighlight lang="clojure">['a 4 11] ; somewhere between array and list |
||
(vector 'a 4 11) |
(vector 'a 4 11) |
||
(cons ['a 4] 11) ; vectors add at the *end*</ |
(cons ['a 4] 11) ; vectors add at the *end*</syntaxhighlight> |
||
===Sets=== |
===Sets=== |
||
< |
<syntaxhighlight lang="clojure">#{:pig :dog :bear} |
||
(assoc #{:pig :bear} :dog) |
(assoc #{:pig :bear} :dog) |
||
(set [:pig :bear :dog])</ |
(set [:pig :bear :dog])</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
Line 637: | Line 637: | ||
{{works with|GnuCOBOL}} |
{{works with|GnuCOBOL}} |
||
< |
<syntaxhighlight lang="cobol"> identification division. |
||
program-id. collections. |
program-id. collections. |
||
Line 673: | Line 673: | ||
goback. |
goback. |
||
end program collections.</ |
end program collections.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 697: | Line 697: | ||
====hashing==== |
====hashing==== |
||
< |
<syntaxhighlight lang="lisp">CL-USER> (let ((list '()) |
||
(hash-table (make-hash-table))) |
(hash-table (make-hash-table))) |
||
(push 1 list) |
(push 1 list) |
||
Line 737: | Line 737: | ||
(3 2 1) |
(3 2 1) |
||
[list] |
[list] |
||
; No value</ |
; No value</syntaxhighlight> |
||
====deque==== |
====deque==== |
||
Line 743: | Line 743: | ||
In Lisp, a deque can be represented using two list variables which are understood to be opposite to each other. That is to say, the list links (cons cell cdr pointers) go inward into the deque from both ends. For instance the deque (1 2 3 4 5 6) can be represented using (1 2 3) and (6 5 4). Then, it is easy to push items on either end using ordinary list push operations. Popping is also simple, except when the case occurs that either piece runs out of items. A Lisp macro can be provided which takes care of this situation. The implementation below handles the underflow in one deque piece by transferring about one half of the elements from the opposite piece. This keeps the amortized cost for pushes and pops O(1), and prevents the degenerate behavior of bouncing all the elements from one side to the other when pops are requested which alternate between the two ends of the deque. |
In Lisp, a deque can be represented using two list variables which are understood to be opposite to each other. That is to say, the list links (cons cell cdr pointers) go inward into the deque from both ends. For instance the deque (1 2 3 4 5 6) can be represented using (1 2 3) and (6 5 4). Then, it is easy to push items on either end using ordinary list push operations. Popping is also simple, except when the case occurs that either piece runs out of items. A Lisp macro can be provided which takes care of this situation. The implementation below handles the underflow in one deque piece by transferring about one half of the elements from the opposite piece. This keeps the amortized cost for pushes and pops O(1), and prevents the degenerate behavior of bouncing all the elements from one side to the other when pops are requested which alternate between the two ends of the deque. |
||
< |
<syntaxhighlight lang="lisp"> |
||
;;; Obtained from Usenet, |
;;; Obtained from Usenet, |
||
;;; Message-ID: <b3b1cc90-2e2b-43c3-b7d9-785ae29870e7@e23g2000prf.googlegroups.com> |
;;; Message-ID: <b3b1cc90-2e2b-43c3-b7d9-785ae29870e7@e23g2000prf.googlegroups.com> |
||
Line 780: | Line 780: | ||
,other-piece ,new-other) |
,other-piece ,new-other) |
||
,result))) |
,result))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Demo: |
Demo: |
||
Line 824: | Line 824: | ||
D has static arrays. |
D has static arrays. |
||
< |
<syntaxhighlight lang="d">int[3] array; |
||
array[0] = 5; |
array[0] = 5; |
||
// array.length = 4; // compile-time error</ |
// array.length = 4; // compile-time error</syntaxhighlight> |
||
D has dynamic arrays. |
D has dynamic arrays. |
||
< |
<syntaxhighlight lang="d">int[] array; |
||
array ~= 5; // append 5 |
array ~= 5; // append 5 |
||
array.length = 3; |
array.length = 3; |
||
array[3] = 17; // runtime error: out of bounds. check removed in release mode. |
array[3] = 17; // runtime error: out of bounds. check removed in release mode. |
||
array = [2, 17, 3]; |
array = [2, 17, 3]; |
||
writefln(array.sort); // 2, 3, 17</ |
writefln(array.sort); // 2, 3, 17</syntaxhighlight> |
||
D has associative arrays. |
D has associative arrays. |
||
< |
<syntaxhighlight lang="d">int[int] array; |
||
// array ~= 5; // it doesn't work that way! |
// array ~= 5; // it doesn't work that way! |
||
array[5] = 17; |
array[5] = 17; |
||
Line 844: | Line 844: | ||
writefln(array.keys, " -> ", array.values); |
writefln(array.keys, " -> ", array.values); |
||
assert(5 in array); // returns a pointer, by the way |
assert(5 in array); // returns a pointer, by the way |
||
if (auto ptr = 6 in array) writefln(*ptr); // 20</ |
if (auto ptr = 6 in array) writefln(*ptr); // 20</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
===Arrays=== |
===Arrays=== |
||
Arrays are collection of values with memory self managed, can be static (size fixed and index not need start in zero) or dynamic (size scaled by user in run time and away start index in zero). |
Arrays are collection of values with memory self managed, can be static (size fixed and index not need start in zero) or dynamic (size scaled by user in run time and away start index in zero). |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
// Creates and initializes a new integer Array |
// Creates and initializes a new integer Array |
||
var |
var |
||
Line 880: | Line 880: | ||
var intArray7: TArray<Integer> := [1, 2, 3]; |
var intArray7: TArray<Integer> := [1, 2, 3]; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
===List=== |
===List=== |
||
Lists are objects and need be release from memory after use. |
Lists are objects and need be release from memory after use. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
var |
var |
||
// TLists can't be initialized or created in declaration scope |
// TLists can't be initialized or created in declaration scope |
||
Line 912: | Line 912: | ||
List4.free; |
List4.free; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Dictionary=== |
===Dictionary=== |
||
TDictionary is a generic class.It represents a collection of key/value pairs. Keys must be unique. |
TDictionary is a generic class.It represents a collection of key/value pairs. Keys must be unique. |
||
It need be release from memory after use. |
It need be release from memory after use. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
var |
var |
||
// TDictionary can't be initialized or created in declaration scope |
// TDictionary can't be initialized or created in declaration scope |
||
Line 936: | Line 936: | ||
Dic3.free; |
Dic3.free; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Queue=== |
===Queue=== |
||
TQueue is a generic class.It represents a collection of data, stored in fist-in fist-out mode. |
TQueue is a generic class.It represents a collection of data, stored in fist-in fist-out mode. |
||
It need be release from memory after use. |
It need be release from memory after use. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
var |
var |
||
Queue1, Queue2: TQueue<Integer>; |
Queue1, Queue2: TQueue<Integer>; |
||
Line 965: | Line 965: | ||
Queue3.free; |
Queue3.free; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Stack=== |
===Stack=== |
||
TStack is a generic class.It represents a collection of data, stored in last-in first-out mode. |
TStack is a generic class.It represents a collection of data, stored in last-in first-out mode. |
||
It need be release from memory after use. |
It need be release from memory after use. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
var |
var |
||
Stack1, Stack2: TStack<Integer>; |
Stack1, Stack2: TStack<Integer>; |
||
Line 994: | Line 994: | ||
Stack3.free; |
Stack3.free; |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Strings=== |
===Strings=== |
||
String are array of chars, start index is one (not zero like almost languages). |
String are array of chars, start index is one (not zero like almost languages). |
||
Can store ansichar (one byte char) or widechar (two bytes char), the default for newer versions is widestring; |
Can store ansichar (one byte char) or widechar (two bytes char), the default for newer versions is widestring; |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
var |
var |
||
Str1:String; // default WideString |
Str1:String; // default WideString |
||
Line 1,026: | Line 1,026: | ||
Writeln(Str1[length(str1)]); // the same above |
Writeln(Str1[length(str1)]); // the same above |
||
end; |
end; |
||
</syntaxhighlight> |
|||
</lang> |
|||
See [[#Pascal]] for more info. |
See [[#Pascal]] for more info. |
||
=={{header|Diego}}== |
=={{header|Diego}}== |
||
Diego operates in the real and abstract world. In the real world, collections exist as scalars, vectors, abilities, specifications, inventories, and, non-fungible tokens: |
Diego operates in the real and abstract world. In the real world, collections exist as scalars, vectors, abilities, specifications, inventories, and, non-fungible tokens: |
||
< |
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me(); |
||
// Real world collections |
// Real world collections |
||
Line 1,056: | Line 1,056: | ||
; |
; |
||
reset_ns[];</ |
reset_ns[];</syntaxhighlight> |
||
In the abstract world, collections exist as variables, stacks, queues, arrays, matricies, clumps, lists, dictionaries, and, hashes: |
In the abstract world, collections exist as variables, stacks, queues, arrays, matricies, clumps, lists, dictionaries, and, hashes: |
||
< |
<syntaxhighlight lang="diego">use_namespace(rosettacode)_me(); |
||
// Abstract world collections |
// Abstract world collections |
||
Line 1,085: | Line 1,085: | ||
add_hash()_ary()_values()_img()_load(/img_027454322.jpg)_img()_load(/img_027454323.jpg); |
add_hash()_ary()_values()_img()_load(/img_027454322.jpg)_img()_load(/img_027454323.jpg); |
||
reset_ns[];</ |
reset_ns[];</syntaxhighlight> |
||
=={{header|E}}== |
=={{header|E}}== |
||
Line 1,091: | Line 1,091: | ||
E has both mutable and immutable builtin collections; the common types are list (array), map (hash table), and set (hash table). This interactive session shows mutable lists and immutable collections of all three types. See also [[Arrays#E]]. |
E has both mutable and immutable builtin collections; the common types are list (array), map (hash table), and set (hash table). This interactive session shows mutable lists and immutable collections of all three types. See also [[Arrays#E]]. |
||
< |
<syntaxhighlight lang="e">? def constList := [1,2,3,4,5] |
||
# value: [1, 2, 3, 4, 5] |
# value: [1, 2, 3, 4, 5] |
||
Line 1,117: | Line 1,117: | ||
? constSet.contains(3) |
? constSet.contains(3) |
||
# value: true</ |
# value: true</syntaxhighlight> |
||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
The collection will be a list, which is not unusual in EchoLisp. We add items - symbols - to the collection, and save it to local storage. |
The collection will be a list, which is not unusual in EchoLisp. We add items - symbols - to the collection, and save it to local storage. |
||
< |
<syntaxhighlight lang="lisp"> |
||
(define my-collection ' ( 🌱 ☀️ ☔️ )) |
(define my-collection ' ( 🌱 ☀️ ☔️ )) |
||
(set! my-collection (cons '🎥 my-collection)) |
(set! my-collection (cons '🎥 my-collection)) |
||
Line 1,131: | Line 1,131: | ||
(local-put 'my-collection) |
(local-put 'my-collection) |
||
→ my-collection |
→ my-collection |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 5.0: |
ELENA 5.0: |
||
===Arrays=== |
===Arrays=== |
||
< |
<syntaxhighlight lang="elena"> |
||
// Weak array |
// Weak array |
||
var stringArr := Array.allocate(5); |
var stringArr := Array.allocate(5); |
||
Line 1,143: | Line 1,143: | ||
// initialized array |
// initialized array |
||
var intArray := new int[]{1, 2, 3, 4, 5}; |
var intArray := new int[]{1, 2, 3, 4, 5}; |
||
</syntaxhighlight> |
|||
</lang> |
|||
===ArrayList and List=== |
===ArrayList and List=== |
||
< |
<syntaxhighlight lang="elena"> |
||
//Create and initialize ArrayList |
//Create and initialize ArrayList |
||
var myAl := new system'collections'ArrayList().append:"Hello".append:"World".append:"!"; |
var myAl := new system'collections'ArrayList().append:"Hello".append:"World".append:"!"; |
||
Line 1,152: | Line 1,152: | ||
//Create and initialize List |
//Create and initialize List |
||
var myList := new system'collections'List().append:"Hello".append:"World".append:"!"; |
var myList := new system'collections'List().append:"Hello".append:"World".append:"!"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Dictionary=== |
===Dictionary=== |
||
< |
<syntaxhighlight lang="elena"> |
||
//Create a dictionary |
//Create a dictionary |
||
var dict := system'collections'Dictionary.new(); |
var dict := system'collections'Dictionary.new(); |
||
dict["Hello"] := "World"; |
dict["Hello"] := "World"; |
||
dict["Key"] := "Value"; |
dict["Key"] := "Value"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
Line 1,169: | Line 1,169: | ||
===List=== |
===List=== |
||
Elixir uses square brackets to specify a list of values. Values can be of any type: |
Elixir uses square brackets to specify a list of values. Values can be of any type: |
||
< |
<syntaxhighlight lang="elixir">empty_list = [] |
||
list = [1,2,3,4,5] |
list = [1,2,3,4,5] |
||
length(list) #=> 5 |
length(list) #=> 5 |
||
Line 1,177: | Line 1,177: | ||
Enum.at(list,3) #=> 4 |
Enum.at(list,3) #=> 4 |
||
list ++ [6,7] #=> [1,2,3,4,5,6,7] |
list ++ [6,7] #=> [1,2,3,4,5,6,7] |
||
list -- [4,2] #=> [1,3,5]</ |
list -- [4,2] #=> [1,3,5]</syntaxhighlight> |
||
===Tuple=== |
===Tuple=== |
||
Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value: |
Elixir uses curly brackets to define tuples. Like lists, tuples can hold any value: |
||
Tuples store elements contiguously in memory. This means accessing a tuple element per index or getting the tuple size is a fast operation: |
Tuples store elements contiguously in memory. This means accessing a tuple element per index or getting the tuple size is a fast operation: |
||
< |
<syntaxhighlight lang="elixir">empty_tuple = {} #=> {} |
||
tuple = {0,1,2,3,4} #=> {0, 1, 2, 3, 4} |
tuple = {0,1,2,3,4} #=> {0, 1, 2, 3, 4} |
||
tuple_size(tuple) #=> 5 |
tuple_size(tuple) #=> 5 |
||
elem(tuple, 2) #=> 2 |
elem(tuple, 2) #=> 2 |
||
put_elem(tuple,3,:atom) #=> {0, 1, 2, :atom, 4}</ |
put_elem(tuple,3,:atom) #=> {0, 1, 2, :atom, 4}</syntaxhighlight> |
||
===Keyword lists=== |
===Keyword lists=== |
||
In Elixir, when we have a list of tuples and the first item of the tuple (i.e. the key) is an atom, we call it a keyword list: |
In Elixir, when we have a list of tuples and the first item of the tuple (i.e. the key) is an atom, we call it a keyword list: |
||
< |
<syntaxhighlight lang="elixir">list = [{:a,1},{:b,2}] #=> [a: 1, b: 2] |
||
list == [a: 1, b: 2] #=> true |
list == [a: 1, b: 2] #=> true |
||
list[:a] #=> 1 |
list[:a] #=> 1 |
||
list ++ [c: 3, a: 5] #=> [a: 1, b: 2, c: 3, a: 5]</ |
list ++ [c: 3, a: 5] #=> [a: 1, b: 2, c: 3, a: 5]</syntaxhighlight> |
||
Keyword lists are important because they have two special characteristics: |
Keyword lists are important because they have two special characteristics: |
||
# They keep the keys ordered, as specified by the developer. |
# They keep the keys ordered, as specified by the developer. |
||
Line 1,203: | Line 1,203: | ||
# Maps allow any value as a key. |
# Maps allow any value as a key. |
||
# Maps' keys do not follow any ordering. |
# Maps' keys do not follow any ordering. |
||
< |
<syntaxhighlight lang="elixir">empty_map = Map.new #=> %{} |
||
kwlist = [x: 1, y: 2] # Key Word List |
kwlist = [x: 1, y: 2] # Key Word List |
||
Map.new(kwlist) #=> %{x: 1, y: 2} |
Map.new(kwlist) #=> %{x: 1, y: 2} |
||
Line 1,217: | Line 1,217: | ||
map = %{:a => 1, :b => 2} #=> %{a: 1, b: 2} |
map = %{:a => 1, :b => 2} #=> %{a: 1, b: 2} |
||
map.a #=> 1 |
map.a #=> 1 |
||
%{map | :a => 2} #=> %{a: 2, b: 2} update only</ |
%{map | :a => 2} #=> %{a: 2, b: 2} update only</syntaxhighlight> |
||
===Set=== |
===Set=== |
||
< |
<syntaxhighlight lang="elixir">empty_set = MapSet.new #=> #MapSet<[]> |
||
set1 = MapSet.new(1..4) #=> #MapSet<[1, 2, 3, 4]> |
set1 = MapSet.new(1..4) #=> #MapSet<[1, 2, 3, 4]> |
||
MapSet.size(set1) #=> 4 |
MapSet.size(set1) #=> 4 |
||
Line 1,229: | Line 1,229: | ||
MapSet.intersection(set1,set2) #=> #MapSet<[2, 4]> |
MapSet.intersection(set1,set2) #=> #MapSet<[2, 4]> |
||
MapSet.difference(set1,set2) #=> #MapSet<[1, 3]> |
MapSet.difference(set1,set2) #=> #MapSet<[1, 3]> |
||
MapSet.subset?(set1,set2) #=> false</ |
MapSet.subset?(set1,set2) #=> false</syntaxhighlight> |
||
===Struct=== |
===Struct=== |
||
Structs are extensions built on top of maps that provide compile-time checks and default values. |
Structs are extensions built on top of maps that provide compile-time checks and default values. |
||
< |
<syntaxhighlight lang="elixir">defmodule User do |
||
defstruct name: "john", age: 27 |
defstruct name: "john", age: 27 |
||
end |
end |
||
Line 1,241: | Line 1,241: | ||
age #=> 27 |
age #=> 27 |
||
meg = %User{name: "meg"} #=> %User{age: 27, name: "meg"} |
meg = %User{name: "meg"} #=> %User{age: 27, name: "meg"} |
||
is_map(meg) #=> true</ |
is_map(meg) #=> true</syntaxhighlight> |
||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: assocs deques dlists lists lists.lazy sequences sets ; |
||
! ===fixed-size sequences=== |
! ===fixed-size sequences=== |
||
Line 1,312: | Line 1,312: | ||
! Factor also comes with disjoint sets, interval maps, heaps, |
! Factor also comes with disjoint sets, interval maps, heaps, |
||
! boxes, directed graphs, locked I/O buffers, trees, and more!</ |
! boxes, directed graphs, locked I/O buffers, trees, and more!</syntaxhighlight> |
||
=={{header|Fancy}}== |
=={{header|Fancy}}== |
||
Line 1,318: | Line 1,318: | ||
===array=== |
===array=== |
||
< |
<syntaxhighlight lang="fancy"> |
||
# creating an empty array and adding values |
# creating an empty array and adding values |
||
Line 1,327: | Line 1,327: | ||
# creating an array with the constructor |
# creating an array with the constructor |
||
a = Array new # => [] |
a = Array new # => [] |
||
</syntaxhighlight> |
|||
</lang> |
|||
===hash=== |
===hash=== |
||
< |
<syntaxhighlight lang="fancy"># creating an empty hash |
||
h = <[]> # => <[]> |
h = <[]> # => <[]> |
||
Line 1,340: | Line 1,340: | ||
# creating a hash with the constructor |
# creating a hash with the constructor |
||
h = Hash new # => <[]> |
h = Hash new # => <[]> |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Line 1,347: | Line 1,347: | ||
===Array=== |
===Array=== |
||
< |
<syntaxhighlight lang="forth">include ffl/car.fs |
||
10 car-create ar \ create a dynamic array with initial size 10 |
10 car-create ar \ create a dynamic array with initial size 10 |
||
Line 1,354: | Line 1,354: | ||
3 1 ar car-set \ ar[1] = 3 |
3 1 ar car-set \ ar[1] = 3 |
||
1 0 ar car-insert \ ar[0] = 1 ar[1] = 2 ar[2] = 3 |
1 0 ar car-insert \ ar[0] = 1 ar[1] = 2 ar[2] = 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Double linked list=== |
===Double linked list=== |
||
< |
<syntaxhighlight lang="forth">include ffl/dcl.fs |
||
dcl-create dl \ create a double linked list |
dcl-create dl \ create a double linked list |
||
Line 1,365: | Line 1,365: | ||
1 dl dcl-prepend |
1 dl dcl-prepend |
||
2 1 dl dcl-insert \ dl[0] = 1 dl[1] = 2 dl[2] = 3 |
2 1 dl dcl-insert \ dl[0] = 1 dl[1] = 2 dl[2] = 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Hashtable=== |
===Hashtable=== |
||
< |
<syntaxhighlight lang="forth">include ffl/hct.fs |
||
10 hct-create ht \ create a hashtable with initial size 10 |
10 hct-create ht \ create a hashtable with initial size 10 |
||
Line 1,376: | Line 1,376: | ||
2 s" two" ht hct-insert \ ht["two"] = 2 |
2 s" two" ht hct-insert \ ht["two"] = 2 |
||
3 s" three" ht hct-insert \ ht["three"] = 3 |
3 s" three" ht hct-insert \ ht["three"] = 3 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
===Standard=== |
===Standard=== |
||
The only facility for a collection more organised than a collection of separately-named variables (even if with a system for the names) is the array, which is a collection of items of identical type, indexed by an integer only, definitely not by a text as in say Snobol. Thus < |
The only facility for a collection more organised than a collection of separately-named variables (even if with a system for the names) is the array, which is a collection of items of identical type, indexed by an integer only, definitely not by a text as in say Snobol. Thus <syntaxhighlight lang="fortran"> REAL A(36) !Declares a one-dimensional array A(1), A(2), ... A(36) |
||
A(1) = 1 !Assigns a value to the first element. |
A(1) = 1 !Assigns a value to the first element. |
||
A(2) = 3*A(1) + 5 !The second element gets 8.</ |
A(2) = 3*A(1) + 5 !The second element gets 8.</syntaxhighlight> |
||
With F90 came a large expansion in the facilities for manipulating arrays. They can now have any lower bound, as in <code>REAL A(-6:+12)</code> and their size can be defined at run time, not just compile time. Further, programmer-defined data aggregates can be defined via the TYPE statement, and arrays of such types can be manipulated. However, type-matching remains rigid: all elements of an array must be of the same type. So, < |
With F90 came a large expansion in the facilities for manipulating arrays. They can now have any lower bound, as in <code>REAL A(-6:+12)</code> and their size can be defined at run time, not just compile time. Further, programmer-defined data aggregates can be defined via the TYPE statement, and arrays of such types can be manipulated. However, type-matching remains rigid: all elements of an array must be of the same type. So, <syntaxhighlight lang="fortran"> TYPE(MIXED) !Name the "type". |
||
INTEGER COUNTER !Its content is listed. |
INTEGER COUNTER !Its content is listed. |
||
REAL WEIGHT,DEPTH |
REAL WEIGHT,DEPTH |
||
Line 1,389: | Line 1,389: | ||
COMPLEX PATH(6) !The mixed collection includes an array. |
COMPLEX PATH(6) !The mixed collection includes an array. |
||
END TYPE MIXED |
END TYPE MIXED |
||
TYPE(MIXED) TEMP,A(6) !Declare some items of that type.</ |
TYPE(MIXED) TEMP,A(6) !Declare some items of that type.</syntaxhighlight> |
||
would define a collection of variables constituting a "type", then a simple variable TEMP whose parts would be accessed via the likes of <code>TEMP.DEPTH</code> or <code>TEMP%DEPTH</code>, and an array of such aggregates where <code> A(3).PATH(1) = (2.7,3.1)</code> assigns a complex number to the first step of the PATH of the third element of array A. The indexing must be associated with the item having an array aspect, but in pl/i <code>A.PATH(3,1)</code> - or other groupings - would be acceptable. |
would define a collection of variables constituting a "type", then a simple variable TEMP whose parts would be accessed via the likes of <code>TEMP.DEPTH</code> or <code>TEMP%DEPTH</code>, and an array of such aggregates where <code> A(3).PATH(1) = (2.7,3.1)</code> assigns a complex number to the first step of the PATH of the third element of array A. The indexing must be associated with the item having an array aspect, but in pl/i <code>A.PATH(3,1)</code> - or other groupings - would be acceptable. |
||
Line 1,402: | Line 1,402: | ||
This can be fixed size or dynamic, have arbitrary lower and upper bounds, have up to 8 dimensions and any kind of element type (including user defined types). Here are some simple examples: |
This can be fixed size or dynamic, have arbitrary lower and upper bounds, have up to 8 dimensions and any kind of element type (including user defined types). Here are some simple examples: |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
'create fixed size array of integers |
'create fixed size array of integers |
||
Line 1,418: | Line 1,418: | ||
Dim c(1 To 2, 1 To 2) As Byte = {{1, 2}, {3, 4}} |
Dim c(1 To 2, 1 To 2) As Byte = {{1, 2}, {3, 4}} |
||
Print c(1, 1), c(2,2) |
Print c(1, 1), c(2,2) |
||
Sleep </ |
Sleep </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,429: | Line 1,429: | ||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=004236066581dd85f39f34e100bf5c40 Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=004236066581dd85f39f34e100bf5c40 Click this link to run this code]''' |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Dim siCount As Short |
Dim siCount As Short |
||
Dim cCollection As Collection = ["0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", |
Dim cCollection As Collection = ["0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", |
||
Line 1,438: | Line 1,438: | ||
Next |
Next |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 1,458: | Line 1,458: | ||
* Maps |
* Maps |
||
Built in resizable collections are slices and maps. The value type for these collections can be any Go type, including interface. An empty interface can reference an object of any type, providing a kind of polymorphic collection. Here the variable <tt>a</tt> is a slice of interface{} objects. |
Built in resizable collections are slices and maps. The value type for these collections can be any Go type, including interface. An empty interface can reference an object of any type, providing a kind of polymorphic collection. Here the variable <tt>a</tt> is a slice of interface{} objects. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 1,467: | Line 1,467: | ||
a = append(a, "apples", "oranges") |
a = append(a, "apples", "oranges") |
||
fmt.Println(a) |
fmt.Println(a) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,484: | Line 1,484: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
Lists are just variable-length, integer-indexed arrays. |
Lists are just variable-length, integer-indexed arrays. |
||
< |
<syntaxhighlight lang="groovy">def emptyList = [] |
||
assert emptyList.isEmpty() : "These are not the items you're looking for" |
assert emptyList.isEmpty() : "These are not the items you're looking for" |
||
assert emptyList.size() == 0 : "Empty list has size 0" |
assert emptyList.size() == 0 : "Empty list has size 0" |
||
Line 1,504: | Line 1,504: | ||
["even more stuff", "even more stuff", "more stuff"] \ |
["even more stuff", "even more stuff", "more stuff"] \ |
||
: "reverse referencing last 3 elements" |
: "reverse referencing last 3 elements" |
||
println ([combinedList: combinedList])</ |
println ([combinedList: combinedList])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,510: | Line 1,510: | ||
Maps are just variable-length, associative arrays. They are not necessarily order preserving. |
Maps are just variable-length, associative arrays. They are not necessarily order preserving. |
||
< |
<syntaxhighlight lang="groovy">def emptyMap = [:] |
||
assert emptyMap.isEmpty() : "These are not the items you're looking for" |
assert emptyMap.isEmpty() : "These are not the items you're looking for" |
||
assert emptyMap.size() == 0 : "Empty map has size 0" |
assert emptyMap.size() == 0 : "Empty map has size 0" |
||
Line 1,533: | Line 1,533: | ||
assert combinedMap.keySet().containsAll( |
assert combinedMap.keySet().containsAll( |
||
["lastName", "count", "eyes", "hair", "weight", "initial", "firstName", "birthdate"]) |
["lastName", "count", "eyes", "hair", "weight", "initial", "firstName", "birthdate"]) |
||
println ([combinedMap: combinedMap])</ |
println ([combinedMap: combinedMap])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,539: | Line 1,539: | ||
Sets are unique, not indexed at all (contents can only be discovered by traversal), and are not necessarily order preserving. There is no particular special language support for denoting a Set, although a Set may be initialized from a List, and Sets share many of the same operations and methods that are available in Lists. |
Sets are unique, not indexed at all (contents can only be discovered by traversal), and are not necessarily order preserving. There is no particular special language support for denoting a Set, although a Set may be initialized from a List, and Sets share many of the same operations and methods that are available in Lists. |
||
< |
<syntaxhighlight lang="groovy">def emptySet = new HashSet() |
||
assert emptySet.isEmpty() : "These are not the items you're looking for" |
assert emptySet.isEmpty() : "These are not the items you're looking for" |
||
assert emptySet.size() == 0 : "Empty set has size 0" |
assert emptySet.size() == 0 : "Empty set has size 0" |
||
Line 1,554: | Line 1,554: | ||
combinedSet << "even more stuff" |
combinedSet << "even more stuff" |
||
assert combinedSet.size() == 5 : "No duplicate elements allowed!" |
assert combinedSet.size() == 5 : "No duplicate elements allowed!" |
||
println ([combinedSet: combinedSet])</ |
println ([combinedSet: combinedSet])</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,563: | Line 1,563: | ||
The list is typically the first collection type to be encountered in textbooks, but other types may tend to be more efficient, or more flexibly accessed; see the <code>Data</code> hierarchy of [http://www.haskell.org/ghc/docs/latest/html/libraries/ GHC's standard library]. New collection types may be defined with <code>data</code>. |
The list is typically the first collection type to be encountered in textbooks, but other types may tend to be more efficient, or more flexibly accessed; see the <code>Data</code> hierarchy of [http://www.haskell.org/ghc/docs/latest/html/libraries/ GHC's standard library]. New collection types may be defined with <code>data</code>. |
||
< |
<syntaxhighlight lang="haskell">[1, 2, 3, 4, 5]</syntaxhighlight> |
||
To prepend a single element to a list, use the <code>:</code> operator: |
To prepend a single element to a list, use the <code>:</code> operator: |
||
< |
<syntaxhighlight lang="haskell">1 : [2, 3, 4]</syntaxhighlight> |
||
To concatenate two lists, use <code>++</code>: |
To concatenate two lists, use <code>++</code>: |
||
< |
<syntaxhighlight lang="haskell">[1, 2] ++ [3, 4]</syntaxhighlight> |
||
To concatenate a whole list of lists, use <code>concat</code>: |
To concatenate a whole list of lists, use <code>concat</code>: |
||
< |
<syntaxhighlight lang="haskell">concat [[1, 2], [3, 4], [5, 6, 7]]</syntaxhighlight> |
||
===Data.Array=== |
===Data.Array=== |
||
Faster retrieval by index: |
Faster retrieval by index: |
||
< |
<syntaxhighlight lang="haskell">import Data.Array (Array, listArray, Ix, (!)) |
||
triples :: Array Int (Char, String, String) |
triples :: Array Int (Char, String, String) |
||
Line 1,597: | Line 1,597: | ||
main :: IO () |
main :: IO () |
||
main = (putStrLn . unlines) $ indexedItem triples <$> [2, 4, 6]</ |
main = (putStrLn . unlines) $ indexedItem triples <$> [2, 4, 6]</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>虎 hǔ tiger |
<pre>虎 hǔ tiger |
||
Line 1,605: | Line 1,605: | ||
===Data.Map=== |
===Data.Map=== |
||
Flexible key-value indexing and efficient retrieval: |
Flexible key-value indexing and efficient retrieval: |
||
< |
<syntaxhighlight lang="haskell">import qualified Data.Map as M |
||
import Data.Maybe (isJust) |
import Data.Maybe (isJust) |
||
Line 1,624: | Line 1,624: | ||
main :: IO () |
main :: IO () |
||
main = |
main = |
||
print $ sequence $ filter isJust (maybeValue <$> ["beta", "delta", "zeta"])</ |
print $ sequence $ filter isJust (maybeValue <$> ["beta", "delta", "zeta"])</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Just [2,4,6]</pre> |
<pre>Just [2,4,6]</pre> |
||
Line 1,630: | Line 1,630: | ||
===Data.Set=== |
===Data.Set=== |
||
Repertoire of efficient set operations: |
Repertoire of efficient set operations: |
||
< |
<syntaxhighlight lang="haskell">import qualified Data.Set as S |
||
setA :: S.Set String |
setA :: S.Set String |
||
Line 1,639: | Line 1,639: | ||
main :: IO () |
main :: IO () |
||
main = (print . S.toList) (S.intersection setA setB)</ |
main = (print . S.toList) (S.intersection setA setB)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>["delta","epsilon"]</pre> |
<pre>["delta","epsilon"]</pre> |
||
Line 1,647: | Line 1,647: | ||
Several data types could be considered collections: |
Several data types could be considered collections: |
||
< |
<syntaxhighlight lang="icon"># Creation of collections: |
||
s := "abccd" # string, an ordered collection of characters, immutable |
s := "abccd" # string, an ordered collection of characters, immutable |
||
c := 'abcd' # cset, an unordered collection of characters, immutable |
c := 'abcd' # cset, an unordered collection of characters, immutable |
||
Line 1,654: | Line 1,654: | ||
L := [] # list, an ordered collection of values indexed by position 1..n or as stack/queue, mutable, contents may be of any type |
L := [] # list, an ordered collection of values indexed by position 1..n or as stack/queue, mutable, contents may be of any type |
||
record constructorname(field1,field2,fieldetc) # record, a collection of values stored in named fields, mutable, contents may be of any type (declare outside procedures) |
record constructorname(field1,field2,fieldetc) # record, a collection of values stored in named fields, mutable, contents may be of any type (declare outside procedures) |
||
R := constructorname() # record (creation)</ |
R := constructorname() # record (creation)</syntaxhighlight> |
||
Adding to these collections can be accomplished as follows: |
Adding to these collections can be accomplished as follows: |
||
<syntaxhighlight lang="icon"> |
|||
<lang Icon> |
|||
s ||:= "xyz" # concatenation |
s ||:= "xyz" # concatenation |
||
c ++:= 'xyz' # union |
c ++:= 'xyz' # union |
||
Line 1,663: | Line 1,663: | ||
T["abc"] := "xyz" # insert create/overwrite |
T["abc"] := "xyz" # insert create/overwrite |
||
put(L,1) # put (extend), also push |
put(L,1) # put (extend), also push |
||
R.field1 := "xyz" # overwrite</ |
R.field1 := "xyz" # overwrite</syntaxhighlight> |
||
Additionally, the following operations apply: |
Additionally, the following operations apply: |
||
<syntaxhighlight lang="icon"> |
|||
<lang Icon> |
|||
S := S ++ S2 # union of two sets or two csets |
S := S ++ S2 # union of two sets or two csets |
||
S ++:= S2 # augmented assignment |
S ++:= S2 # augmented assignment |
||
L := L ||| L2 # list concatenation |
L := L ||| L2 # list concatenation |
||
L |||:= L2 # augmented assignment</ |
L |||:= L2 # augmented assignment</syntaxhighlight> |
||
=={{header|J}}== |
=={{header|J}}== |
||
Line 1,677: | Line 1,677: | ||
J will, when possible without losing significance of the original value, implicitly convert values to a type which allows them represented in a homogeneous fashion in a collection. Heterogeneous collections are possible via "boxing" (analogous to a "variant" data type). |
J will, when possible without losing significance of the original value, implicitly convert values to a type which allows them represented in a homogeneous fashion in a collection. Heterogeneous collections are possible via "boxing" (analogous to a "variant" data type). |
||
< |
<syntaxhighlight lang="j"> c =: 0 10 20 30 40 NB. A collection |
||
c, 50 NB. Append 50 to the collection |
c, 50 NB. Append 50 to the collection |
||
Line 1,763: | Line 1,763: | ||
1 1 1 1 1 |
1 1 1 1 1 |
||
c -: 10 i.5 NB. Test for identicality |
c -: 10 i.5 NB. Test for identicality |
||
1</ |
1</syntaxhighlight> |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
Line 1,771: | Line 1,771: | ||
When creating a List of any kind in Java (Arraylist or LinkedList), the type of the variable is a style choice. It is sometimes considered good practice to make the pointer of type List and the new object of a List subclass. Doing this will ensure two things: if you need to change the type of list you want you only need to change one line and all of your methods will still work, and you will not be able to use any methods that are specific to the List type you chose. So in this example, all instances of "ArrayList" can be changed to "LinkedList" and it will still work, but you will not be able to use a method like "ensureCapactiy()" because the variable is of type List. |
When creating a List of any kind in Java (Arraylist or LinkedList), the type of the variable is a style choice. It is sometimes considered good practice to make the pointer of type List and the new object of a List subclass. Doing this will ensure two things: if you need to change the type of list you want you only need to change one line and all of your methods will still work, and you will not be able to use any methods that are specific to the List type you chose. So in this example, all instances of "ArrayList" can be changed to "LinkedList" and it will still work, but you will not be able to use a method like "ensureCapactiy()" because the variable is of type List. |
||
< |
<syntaxhighlight lang="java5">List arrayList = new ArrayList(); |
||
arrayList.add(new Integer(0)); |
arrayList.add(new Integer(0)); |
||
// alternative with primitive autoboxed to an Integer object automatically |
// alternative with primitive autoboxed to an Integer object automatically |
||
Line 1,784: | Line 1,784: | ||
for(int i = 0; i < 10; i++) { |
for(int i = 0; i < 10; i++) { |
||
myarrlist.add(i); |
myarrlist.add(i); |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="java5">//loop through myarrlist to sum each entry |
||
for ( i = 0; i < myarrlist.size(); i++) { |
for ( i = 0; i < myarrlist.size(); i++) { |
||
sum += myarrlist.get(i); |
sum += myarrlist.get(i); |
||
}</ |
}</syntaxhighlight> |
||
or |
or |
||
< |
<syntaxhighlight lang="java5">for(int i : myarrlist) { |
||
sum += i; |
sum += i; |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="java5">//remove the last entry in the ArrayList |
||
myarrlist.remove(myarrlist.size()-1) |
myarrlist.remove(myarrlist.size()-1) |
||
//clear the ArrayList |
//clear the ArrayList |
||
myarrlist.clear();</ |
myarrlist.clear();</syntaxhighlight> |
||
Here is a reference table for characteristics of commonly used <code>Collections</code> classes: |
Here is a reference table for characteristics of commonly used <code>Collections</code> classes: |
||
{|class="wikitable" |
{|class="wikitable" |
||
Line 1,843: | Line 1,843: | ||
|} |
|} |
||
=== Using the Scala collection classes=== |
=== Using the Scala collection classes=== |
||
The [[Scala|Scala]] libraries are valid Java byte-code libraries. The collection part of these are rich because the multiple inheritance by traits. E.g. an [http://www.scala-lang.org/api/current/index.html#scala.collection.mutable.ArrayBuffer ArrayBuffer] has properties inherent of 9 traits such as Buffer[A], IndexedSeqOptimized[A, ArrayBuffer[A]], Builder[A, ArrayBuffer[A]], ResizableArray[A] and Serializable. Another collection e.g. TrieMap uses some of these and other added traits. A [http://www.scala-lang.org/api/current/index.html#scala.collection.concurrent.TrieMap TrieMap] -a hashmap- is the most advanced of all. It supports parallel processing without blocking.< |
The [[Scala|Scala]] libraries are valid Java byte-code libraries. The collection part of these are rich because the multiple inheritance by traits. E.g. an [http://www.scala-lang.org/api/current/index.html#scala.collection.mutable.ArrayBuffer ArrayBuffer] has properties inherent of 9 traits such as Buffer[A], IndexedSeqOptimized[A, ArrayBuffer[A]], Builder[A, ArrayBuffer[A]], ResizableArray[A] and Serializable. Another collection e.g. TrieMap uses some of these and other added traits. A [http://www.scala-lang.org/api/current/index.html#scala.collection.concurrent.TrieMap TrieMap] -a hashmap- is the most advanced of all. It supports parallel processing without blocking.<syntaxhighlight lang="java5">import scala.Tuple2; |
||
import scala.collection.concurrent.TrieMap; |
import scala.collection.concurrent.TrieMap; |
||
import scala.collection.immutable.HashSet; |
import scala.collection.immutable.HashSet; |
||
Line 1,893: | Line 1,893: | ||
} |
} |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
< |
<syntaxhighlight lang="javascript">var array = []; |
||
array.push('abc'); |
array.push('abc'); |
||
array.push(123); |
array.push(123); |
||
array.push(new MyClass); |
array.push(new MyClass); |
||
console.log( array[2] );</ |
console.log( array[2] );</syntaxhighlight> |
||
< |
<syntaxhighlight lang="javascript">var obj = {}; |
||
obj['foo'] = 'xyz'; //equivalent to: obj.foo = 'xyz'; |
obj['foo'] = 'xyz'; //equivalent to: obj.foo = 'xyz'; |
||
obj['bar'] = new MyClass; //equivalent to: obj.bar = new MyClass; |
obj['bar'] = new MyClass; //equivalent to: obj.bar = new MyClass; |
||
obj['1x; ~~:-b'] = 'text'; //no equivalent |
obj['1x; ~~:-b'] = 'text'; //no equivalent |
||
console.log(obj['1x; ~~:-b']);</ |
console.log(obj['1x; ~~:-b']);</syntaxhighlight> |
||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 1,919: | Line 1,919: | ||
One of the programmatic approaches to creating JSON objects allows |
One of the programmatic approaches to creating JSON objects allows |
||
the key names to be specified as unquoted strings, e.g. |
the key names to be specified as unquoted strings, e.g. |
||
< |
<syntaxhighlight lang="jq">{"a": 1} == {a: 1}</syntaxhighlight> |
||
evaluates to true. Variables can also be used, e.g. the object {"a":1} can also be created by the following |
evaluates to true. Variables can also be used, e.g. the object {"a":1} can also be created by the following |
||
pipeline: |
pipeline: |
||
< |
<syntaxhighlight lang="jq">"a" as $key | 1 as $value | {($key): $value}</syntaxhighlight> |
||
===Equality=== |
===Equality=== |
||
Line 1,937: | Line 1,937: | ||
modifying an element of a composite structure. For example, consider the following pipeline: |
modifying an element of a composite structure. For example, consider the following pipeline: |
||
< |
<syntaxhighlight lang="jq">[0,1,2] | .[0] = 10</syntaxhighlight> |
||
The result (or output) of this sequence is [10,1,2], so it is convenient to |
The result (or output) of this sequence is [10,1,2], so it is convenient to |
||
Line 1,945: | Line 1,945: | ||
Julia has a wide variety of collections, including vectors, matrices, lists of Any data type, associative arrays, and bitsets. |
Julia has a wide variety of collections, including vectors, matrices, lists of Any data type, associative arrays, and bitsets. |
||
There is a slicing notation and list comprehensions similar to those in Python, but the base index is by default 1, not 0. In Julia, a collection is a just variable length array: |
There is a slicing notation and list comprehensions similar to those in Python, but the base index is by default 1, not 0. In Julia, a collection is a just variable length array: |
||
< |
<syntaxhighlight lang="julia"> |
||
julia> collection = [] |
julia> collection = [] |
||
Line 1,956: | Line 1,956: | ||
4 |
4 |
||
7 |
7 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
Line 1,962: | Line 1,962: | ||
In addition, Kotlin can also access other types of Java collection such as LinkedList, Queue, Deque and Stack by simply importing the appropriate type: |
In addition, Kotlin can also access other types of Java collection such as LinkedList, Queue, Deque and Stack by simply importing the appropriate type: |
||
< |
<syntaxhighlight lang="scala">import java.util.PriorityQueue |
||
fun main(args: Array<String>) { |
fun main(args: Array<String>) { |
||
Line 2,004: | Line 2,004: | ||
pq.add("First"); pq.add("Second"); pq.add("Third") |
pq.add("First"); pq.add("Second"); pq.add("Third") |
||
println(pq) |
println(pq) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,021: | Line 2,021: | ||
=={{header|Lingo}}== |
=={{header|Lingo}}== |
||
Lingo has 2 collection types: lists (arrays) and property lists (hashes): |
Lingo has 2 collection types: lists (arrays) and property lists (hashes): |
||
< |
<syntaxhighlight lang="lingo">-- list stuff |
||
l = [1, 2] |
l = [1, 2] |
||
l.add(3) |
l.add(3) |
||
Line 2,033: | Line 2,033: | ||
pl["barfoo"] = 4 |
pl["barfoo"] = 4 |
||
put pl |
put pl |
||
-- [#foo: 1, #bar: 2, #foobar: 3, "barfoo": 4]</ |
-- [#foo: 1, #bar: 2, #foobar: 3, "barfoo": 4]</syntaxhighlight> |
||
Lingo is not statically-typed, but if needed, a collection type that only accepts a specific data type can be created by sub-classing one of the 2 available collection types and overwriting its access methods, so that those block any data type other than the one that was passed to the constructor. |
Lingo is not statically-typed, but if needed, a collection type that only accepts a specific data type can be created by sub-classing one of the 2 available collection types and overwriting its access methods, so that those block any data type other than the one that was passed to the constructor. |
||
Line 2,039: | Line 2,039: | ||
=={{header|Lisaac}}== |
=={{header|Lisaac}}== |
||
===vector=== |
===vector=== |
||
< |
<syntaxhighlight lang="lisaac">+ vector : ARRAY[INTEGER]; |
||
vector := ARRAY[INTEGER].create_with_capacity 32 lower 0; |
vector := ARRAY[INTEGER].create_with_capacity 32 lower 0; |
||
vector.add_last 1; |
vector.add_last 1; |
||
vector.add_last 2;</ |
vector.add_last 2;</syntaxhighlight> |
||
===hashed set=== |
===hashed set=== |
||
< |
<syntaxhighlight lang="lisaac">+ set : HASHED_SET[INTEGER]; |
||
set := HASHED_SET[INTEGER].create; |
set := HASHED_SET[INTEGER].create; |
||
set.add 1; |
set.add 1; |
||
set.add 2;</ |
set.add 2;</syntaxhighlight> |
||
===linked list=== |
===linked list=== |
||
< |
<syntaxhighlight lang="lisaac">+ list : LINKED_LIST[INTEGER]; |
||
list := LINKED_LIST[INTEGER].create; |
list := LINKED_LIST[INTEGER].create; |
||
list.add_last 1; |
list.add_last 1; |
||
list.add_last 2;</ |
list.add_last 2;</syntaxhighlight> |
||
===hashed dictionary=== |
===hashed dictionary=== |
||
< |
<syntaxhighlight lang="lisaac">+ dict : HASHED_DICTIONARY[INTEGER/*value*/, STRING_CONSTANT/*key*/]; |
||
dict := HASHED_DICTIONARY[INTEGER, STRING_CONSTANT].create; |
dict := HASHED_DICTIONARY[INTEGER, STRING_CONSTANT].create; |
||
dict.put 1 to "one"; |
dict.put 1 to "one"; |
||
dict.put 2 to "two";</ |
dict.put 2 to "two";</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
Line 2,068: | Line 2,068: | ||
Lua has only one type of collection, the table. But Lua's table has features of both, traditional arrays and hash maps (dictionaries). You can even mix both within one table. Note, that the numeric indices of Lua's table start at 1, not at 0 as with most other languages. |
Lua has only one type of collection, the table. But Lua's table has features of both, traditional arrays and hash maps (dictionaries). You can even mix both within one table. Note, that the numeric indices of Lua's table start at 1, not at 0 as with most other languages. |
||
< |
<syntaxhighlight lang="lua">collection = {0, '1'} |
||
print(collection[1]) -- prints 0 |
print(collection[1]) -- prints 0 |
||
Line 2,075: | Line 2,075: | ||
print(collection.foo) -- syntactic sugar, also prints 0 |
print(collection.foo) -- syntactic sugar, also prints 0 |
||
collection = {0, '1', ["foo"] = 0, ["bar"] = '1'}</ |
collection = {0, '1', ["foo"] = 0, ["bar"] = '1'}</syntaxhighlight> |
||
It is idiomatic in Lua to represent a Set data structure with a table of keys to the true value. |
It is idiomatic in Lua to represent a Set data structure with a table of keys to the true value. |
||
Line 2,081: | Line 2,081: | ||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
===Ordered List (array)=== |
===Ordered List (array)=== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Arr { |
Module Arr { |
||
\\ array as tuple |
\\ array as tuple |
||
Line 2,096: | Line 2,096: | ||
} |
} |
||
Arr |
Arr |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Ordered List (stack)=== |
===Ordered List (stack)=== |
||
A stack may have values inventories,arrays, stacks, groups |
A stack may have values inventories,arrays, stacks, groups |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module CheckStack { |
Module CheckStack { |
||
\\ ordered collection: Stack |
\\ ordered collection: Stack |
||
Line 2,136: | Line 2,136: | ||
} |
} |
||
CheckStack |
CheckStack |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Inventories as Maps=== |
===Inventories as Maps=== |
||
An Inventory may have values inventories,arrays, stacks, groups |
An Inventory may have values inventories,arrays, stacks, groups |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Maps { |
Module Maps { |
||
\\ Inventory as pairs of keys/values |
\\ Inventory as pairs of keys/values |
||
Line 2,168: | Line 2,168: | ||
} |
} |
||
Maps |
Maps |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Inventories as Sets=== |
===Inventories as Sets=== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Sets { |
Module Sets { |
||
\\ Inventory as set of keys |
\\ Inventory as set of keys |
||
Line 2,203: | Line 2,203: | ||
} |
} |
||
Sets |
Sets |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Using a Visual Basic 6 Collection=== |
===Using a Visual Basic 6 Collection=== |
||
Line 2,209: | Line 2,209: | ||
We can get a list |
We can get a list |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module GetC { |
Module GetC { |
||
declare c collection |
declare c collection |
||
Line 2,260: | Line 2,260: | ||
Read a |
Read a |
||
Print type$(a)="Collection" ' if we don't declare |
Print type$(a)="Collection" ' if we don't declare |
||
</syntaxhighlight> |
|||
</lang> |
|||
{Out} |
{Out} |
||
<pre> |
<pre> |
||
Line 2,288: | Line 2,288: | ||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
Defining lists: |
Defining lists: |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
L1 := [3, 4, 5, 6]; |
L1 := [3, 4, 5, 6]; |
||
L1 := [3, 4, 5, 6] |
L1 := [3, 4, 5, 6] |
||
Line 2,294: | Line 2,294: | ||
L2 := [7, 8, 9]; |
L2 := [7, 8, 9]; |
||
L2 := [7, 8, 9] |
L2 := [7, 8, 9] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Concatenating two lists: |
Concatenating two lists: |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
[op(L1), op(L2)] |
[op(L1), op(L2)] |
||
[3, 4, 5, 6, 7, 8, 9] |
[3, 4, 5, 6, 7, 8, 9] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Defining an Array: |
Defining an Array: |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
A1 := Array([3, 4, 5, 6]); |
A1 := Array([3, 4, 5, 6]); |
||
A1 := [3, 4, 5, 6] |
A1 := [3, 4, 5, 6] |
||
</syntaxhighlight> |
|||
</lang> |
|||
Appending to a Vector: |
Appending to a Vector: |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
ArrayTools:-Append(A1, 7); |
ArrayTools:-Append(A1, 7); |
||
A1 := [3, 4, 5, 6, 7] |
A1 := [3, 4, 5, 6, 7] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">Lst = {3, 4, 5, 6} |
||
->{3, 4, 5, 6} |
->{3, 4, 5, 6} |
||
Line 2,326: | Line 2,326: | ||
Insert[ Lst, X, 4] |
Insert[ Lst, X, 4] |
||
->{1, 2, 3, X, 4, 5, 6}</ |
->{1, 2, 3, X, 4, 5, 6}</syntaxhighlight> |
||
=={{header|MATLAB}} / {{header|Octave}}== |
=={{header|MATLAB}} / {{header|Octave}}== |
||
Line 2,332: | Line 2,332: | ||
Sample Usage: |
Sample Usage: |
||
< |
<syntaxhighlight lang="matlab">>> A = {2,'TPS Report'} %Declare cell-array and initialize |
||
A = |
A = |
||
Line 2,355: | Line 2,355: | ||
make: 'honda' |
make: 'honda' |
||
year: 2003</ |
year: 2003</syntaxhighlight> |
||
'''Bold text''' |
'''Bold text''' |
||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
MiniScript supports both lists and maps (dictionaries). This task demonstrates lists. |
MiniScript supports both lists and maps (dictionaries). This task demonstrates lists. |
||
< |
<syntaxhighlight lang="miniscript">seq = [0, "foo", pi] |
||
seq.push 42 |
seq.push 42 |
||
seq = seq + [1, 2, 3] |
seq = seq + [1, 2, 3] |
||
print seq</ |
print seq</syntaxhighlight> |
||
{{output}} |
{{output}} |
||
Line 2,370: | Line 2,370: | ||
=={{header|MS SmallBasic}}== |
=={{header|MS SmallBasic}}== |
||
Only with LD extension |
Only with LD extension |
||
<syntaxhighlight lang="mssmallbasic"> |
|||
<lang MSsmallbasic> |
|||
ll=LDList.CreateFromValues("") |
ll=LDList.CreateFromValues("") |
||
LDList.Add(ll "Cars") |
LDList.Add(ll "Cars") |
||
LDList.Add(ll "Toys") |
LDList.Add(ll "Toys") |
||
LDList.Print(ll) |
LDList.Print(ll) |
||
</syntaxhighlight> |
|||
</lang> |
|||
result: |
result: |
||
Line 2,386: | Line 2,386: | ||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
NetRexx can take advantage of Java's <tt>Collection</tt> classes. This example uses the <tt>Set</tt> interface backed by a <tt>HashSet</tt>: |
NetRexx can take advantage of Java's <tt>Collection</tt> classes. This example uses the <tt>Set</tt> interface backed by a <tt>HashSet</tt>: |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref symbols nobinary |
options replace format comments java crossref symbols nobinary |
||
Line 2,402: | Line 2,402: | ||
return |
return |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
===Array=== |
===Array=== |
||
Length is known at compile time |
Length is known at compile time |
||
< |
<syntaxhighlight lang="nim">var a = [1,2,3,4,5,6,7,8,9] |
||
var b: array[128, int] |
var b: array[128, int] |
||
b[9] = 10 |
b[9] = 10 |
||
b[0..8] = a |
b[0..8] = a |
||
var c: array['a'..'d', float] = [1.0, 1.1, 1.2, 1.3] |
var c: array['a'..'d', float] = [1.0, 1.1, 1.2, 1.3] |
||
c['b'] = 10000</ |
c['b'] = 10000</syntaxhighlight> |
||
===Seq=== |
===Seq=== |
||
Variable length sequences |
Variable length sequences |
||
< |
<syntaxhighlight lang="nim">var d = @[1,2,3,5,6,7,8,9] |
||
d.add(10) |
d.add(10) |
||
d.add([11,12,13,14]) |
d.add([11,12,13,14]) |
||
Line 2,426: | Line 2,426: | ||
var f = newSeq[string]() |
var f = newSeq[string]() |
||
f.add("foo") |
f.add("foo") |
||
f.add("bar")</ |
f.add("bar")</syntaxhighlight> |
||
===Tuple=== |
===Tuple=== |
||
Fixed length, named |
Fixed length, named |
||
< |
<syntaxhighlight lang="nim">var g = (13, 13, 14) |
||
g[0] = 12 |
g[0] = 12 |
||
Line 2,436: | Line 2,436: | ||
# A sequence of key-val tuples: |
# A sequence of key-val tuples: |
||
var i = {"foo": 12, "bar": 13}</ |
var i = {"foo": 12, "bar": 13}</syntaxhighlight> |
||
===Set=== |
===Set=== |
||
Bit vector of ordinals |
Bit vector of ordinals |
||
< |
<syntaxhighlight lang="nim">var j: set[char] |
||
j.incl('X') |
j.incl('X') |
||
var k = {'a'..'z', '0'..'9'} |
var k = {'a'..'z', '0'..'9'} |
||
j = j + k</ |
j = j + k</syntaxhighlight> |
||
===Tables=== |
===Tables=== |
||
Hash tables (there are also ordered hash tables and counting hash tables) |
Hash tables (there are also ordered hash tables and counting hash tables) |
||
< |
<syntaxhighlight lang="nim">import tables |
||
var l = initTable[string, int]() |
var l = initTable[string, int]() |
||
l["foo"] = 12 |
l["foo"] = 12 |
||
Line 2,455: | Line 2,455: | ||
var m = {"foo": 12, "bar": 13}.toTable |
var m = {"foo": 12, "bar": 13}.toTable |
||
m["baz"] = 14</ |
m["baz"] = 14</syntaxhighlight> |
||
===Sets=== |
===Sets=== |
||
Hash sets (also ordered hash sets) |
Hash sets (also ordered hash sets) |
||
< |
<syntaxhighlight lang="nim">import sets |
||
var n = initSet[string]() |
var n = initSet[string]() |
||
n.incl("foo") |
n.incl("foo") |
||
var o = ["foo", "bar", "baz"].toSet |
var o = ["foo", "bar", "baz"].toSet |
||
o.incl("foobar")</ |
o.incl("foobar")</syntaxhighlight> |
||
===Double queues=== |
===Double queues=== |
||
< |
<syntaxhighlight lang="nim">import deques |
||
var p = initDeque[int]() |
var p = initDeque[int]() |
||
p.addLast(12) |
p.addLast(12) |
||
p.addFirst(13) |
p.addFirst(13) |
||
echo p.popFirst() |
echo p.popFirst() |
||
echo p.popLast()</ |
echo p.popLast()</syntaxhighlight> |
||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
===vector=== |
===vector=== |
||
< |
<syntaxhighlight lang="objeck"> |
||
values := IntVector->New(); |
values := IntVector->New(); |
||
values->AddBack(7); |
values->AddBack(7); |
||
values->AddBack(3); |
values->AddBack(3); |
||
values->AddBack(10); |
values->AddBack(10); |
||
</syntaxhighlight> |
|||
</lang> |
|||
===linked list=== |
===linked list=== |
||
< |
<syntaxhighlight lang="objeck"> |
||
values := IntList->New(); |
values := IntList->New(); |
||
values->AddBack(7); |
values->AddBack(7); |
||
values->AddBack(3); |
values->AddBack(3); |
||
values->AddBack(10); |
values->AddBack(10); |
||
</syntaxhighlight> |
|||
</lang> |
|||
===hash=== |
===hash=== |
||
< |
<syntaxhighlight lang="objeck"> |
||
values := StringHash->New(); |
values := StringHash->New(); |
||
values->Insert("seven", IntHolder->New(7)); |
values->Insert("seven", IntHolder->New(7)); |
||
values->Insert("three", IntHolder->New(3)); |
values->Insert("three", IntHolder->New(3)); |
||
values->Insert("ten", IntHolder->New(10)); |
values->Insert("ten", IntHolder->New(10)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
===stack=== |
===stack=== |
||
< |
<syntaxhighlight lang="objeck"> |
||
values := IntStack->New(); |
values := IntStack->New(); |
||
values->Push(7); |
values->Push(7); |
||
values->Push(3); |
values->Push(3); |
||
values->Push(10); |
values->Push(10); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Objective-C}}== |
=={{header|Objective-C}}== |
||
Line 2,514: | Line 2,514: | ||
Arrays (indexed by an integer), which are also collections, are not shown here. |
Arrays (indexed by an integer), which are also collections, are not shown here. |
||
< |
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h> |
||
void show_collection(id coll) |
void show_collection(id coll) |
||
Line 2,563: | Line 2,563: | ||
} |
} |
||
return EXIT_SUCCESS; |
return EXIT_SUCCESS; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} (stripped the left-sided log info): |
{{out}} (stripped the left-sided log info): |
||
Line 2,581: | Line 2,581: | ||
Lists are written like so: |
Lists are written like so: |
||
< |
<syntaxhighlight lang="ocaml">[1; 2; 3; 4; 5]</syntaxhighlight> |
||
To prepend a single element to a list, use the '''::''' operator: |
To prepend a single element to a list, use the '''::''' operator: |
||
< |
<syntaxhighlight lang="ocaml">1 :: [2; 3; 4; 5]</syntaxhighlight> |
||
To concatenate two lists, use '''@''': |
To concatenate two lists, use '''@''': |
||
< |
<syntaxhighlight lang="ocaml">[1; 2] @ [3; 4; 5]</syntaxhighlight> |
||
To concatenate a whole list of lists, use [http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html#VALflatten List.flatten]: |
To concatenate a whole list of lists, use [http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html#VALflatten List.flatten]: |
||
< |
<syntaxhighlight lang="ocaml"># List.flatten [[1; 2]; [3; 4]; [5; 6; 7]] ;; |
||
- : int list = [1; 2; 3; 4; 5; 6; 7]</ |
- : int list = [1; 2; 3; 4; 5; 6; 7]</syntaxhighlight> |
||
Being a ''functional'' programming language, the list is one of the most important collection type. And being an ''impure'' functional programming language there are also imperative collection type, as for example, arrays: |
Being a ''functional'' programming language, the list is one of the most important collection type. And being an ''impure'' functional programming language there are also imperative collection type, as for example, arrays: |
||
< |
<syntaxhighlight lang="ocaml">[| 1; 2; 3; 4; 5 |]</syntaxhighlight> |
||
The [http://code.google.com/p/ocaml-extlib/ extlib] also provides a type [http://ocaml-extlib.googlecode.com/svn/doc/apiref/Enum.html Enum.t]. |
The [http://code.google.com/p/ocaml-extlib/ extlib] also provides a type [http://ocaml-extlib.googlecode.com/svn/doc/apiref/Enum.html Enum.t]. |
||
Line 2,618: | Line 2,618: | ||
A List (or a Pair) can be created using the following syntax : |
A List (or a Pair) can be created using the following syntax : |
||
< |
<syntaxhighlight lang="oforth">[ 1, 1.2, "abcd", [ 1, 2, 3 ] ]</syntaxhighlight> |
||
In order to add values to a collection, you have to use a ListBuffer (a mutable collection) : |
In order to add values to a collection, you have to use a ListBuffer (a mutable collection) : |
||
< |
<syntaxhighlight lang="oforth">ListBuffer new dup add(10) dup add("aaa") dup add(Date now) dup add(1.3) println </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,634: | Line 2,634: | ||
ooRexx arrays are sequential lists of object references. The index values are the numeric position (1-based) within the array. |
ooRexx arrays are sequential lists of object references. The index values are the numeric position (1-based) within the array. |
||
A given array may be sparse and arrays will be automatically expanded as needed. |
A given array may be sparse and arrays will be automatically expanded as needed. |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
a = .array~new(4) -- creates an array of 4 items, with all slots empty |
a = .array~new(4) -- creates an array of 4 items, with all slots empty |
||
say a~size a~items -- size is 4, but there are 0 items |
say a~size a~items -- size is 4, but there are 0 items |
||
Line 2,640: | Line 2,640: | ||
a[5] = "Mike" -- assigns a value to the fifth slot, expanding the size |
a[5] = "Mike" -- assigns a value to the fifth slot, expanding the size |
||
say a~size a~items -- size is now 5, with 2 items |
say a~size a~items -- size is now 5, with 2 items |
||
</syntaxhighlight> |
|||
</lang> |
|||
;Lists |
;Lists |
||
Line 2,646: | Line 2,646: | ||
and the positions will be adjusted accordingly. Lists are indexed using index cookies that are assigned when |
and the positions will be adjusted accordingly. Lists are indexed using index cookies that are assigned when |
||
an entry is added to the list and can be used to access entries or traverse through the list. |
an entry is added to the list and can be used to access entries or traverse through the list. |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
l = .list~new -- lists have no inherent size |
l = .list~new -- lists have no inherent size |
||
index = l~insert('123') -- adds an item to this list, returning the index |
index = l~insert('123') -- adds an item to this list, returning the index |
||
Line 2,656: | Line 2,656: | ||
say item |
say item |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,668: | Line 2,668: | ||
Queues are non-sparse sequential lists of object references. The index values are by numeric position (1-based), although access to |
Queues are non-sparse sequential lists of object references. The index values are by numeric position (1-based), although access to |
||
items is traditionally done by pushing or popping objects. |
items is traditionally done by pushing or popping objects. |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
q = .queue~of(2,4,6) -- creates a queue containing 3 items |
q = .queue~of(2,4,6) -- creates a queue containing 3 items |
||
say q[1] q[3] -- displays "2 6" |
say q[1] q[3] -- displays "2 6" |
||
Line 2,676: | Line 2,676: | ||
q[1] = q[1] + 1 -- updates the first item |
q[1] = q[1] + 1 -- updates the first item |
||
say q[1] q[3] -- displays "5 2" |
say q[1] q[3] -- displays "5 2" |
||
</syntaxhighlight> |
|||
</lang> |
|||
;Tables |
;Tables |
||
Tables are collections that create a one-to-one relationship between an index object and a referenced object. |
Tables are collections that create a one-to-one relationship between an index object and a referenced object. |
||
Although frequently used with string indexes, the index object can be of any class, with index identity determined by the "==" method. |
Although frequently used with string indexes, the index object can be of any class, with index identity determined by the "==" method. |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
t = .table~new |
t = .table~new |
||
t['abc'] = 1 |
t['abc'] = 1 |
||
t['def'] = 2 |
t['def'] = 2 |
||
say t['abc'] t['def'] -- displays "1 2" |
say t['abc'] t['def'] -- displays "1 2" |
||
</syntaxhighlight> |
|||
</lang> |
|||
;Relations |
;Relations |
||
Relation collections create one-to-many data relationships. An addition to the collection will always create a new entry. |
Relation collections create one-to-many data relationships. An addition to the collection will always create a new entry. |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
t = .table~new -- a table example to demonstrate the difference |
t = .table~new -- a table example to demonstrate the difference |
||
t['abc'] = 1 -- sets an item at index 'abc' |
t['abc'] = 1 -- sets an item at index 'abc' |
||
Line 2,703: | Line 2,703: | ||
say item |
say item |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
;Directories |
;Directories |
||
Directory objects are like tables, but the index values must always be string objects. |
Directory objects are like tables, but the index values must always be string objects. |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
d = .directory~new |
d = .directory~new |
||
d['abc'] = 1 |
d['abc'] = 1 |
||
d['def'] = 2 |
d['def'] = 2 |
||
say d['abc'] d['def'] -- displays "1 2" |
say d['abc'] d['def'] -- displays "1 2" |
||
</syntaxhighlight> |
|||
</lang> |
|||
Directory objects also support an UNKNOWN method that map messages to directory index entries. This allows |
Directory objects also support an UNKNOWN method that map messages to directory index entries. This allows |
||
values to be set as if they were object attributes. The following example is another way of doing the same as |
values to be set as if they were object attributes. The following example is another way of doing the same as |
||
the first example: |
the first example: |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
d = .directory~new |
d = .directory~new |
||
d~abc = 1 |
d~abc = 1 |
||
d~def = 2 |
d~def = 2 |
||
say d~abc d~def -- displays "1 2" |
say d~abc d~def -- displays "1 2" |
||
</syntaxhighlight> |
|||
</lang> |
|||
Note that the index entries created in the example are the uppercase 'ABC' and 'DEF'. |
Note that the index entries created in the example are the uppercase 'ABC' and 'DEF'. |
||
Line 2,727: | Line 2,727: | ||
Sets are unordered collections where the items added to the collection are unique values. Duplicate additions are collapsed to just a |
Sets are unordered collections where the items added to the collection are unique values. Duplicate additions are collapsed to just a |
||
single item. Sets are useful for collecting unique occurrences of items. |
single item. Sets are useful for collecting unique occurrences of items. |
||
<syntaxhighlight lang="oorexx"> |
|||
<lang ooRexx> |
|||
s = .set~new |
s = .set~new |
||
text = "the quick brown fox jumped over the lazy dog" |
text = "the quick brown fox jumped over the lazy dog" |
||
Line 2,735: | Line 2,735: | ||
say "text has" text~words", but only" s~items "unique words" |
say "text has" text~words", but only" s~items "unique words" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
The most important collection types are lists, records, dictionaries and arrays: |
The most important collection types are lists, records, dictionaries and arrays: |
||
< |
<syntaxhighlight lang="oz">declare |
||
%% Lists (immutable, recursive) |
%% Lists (immutable, recursive) |
||
Xs = [1 2 3 4] |
Xs = [1 2 3 4] |
||
Line 2,763: | Line 2,763: | ||
Arr = {Array.new 1 10 initValue} |
Arr = {Array.new 1 10 initValue} |
||
Arr.1 := 3 |
Arr.1 := 3 |
||
{Show Arr.1} %% output: 3</ |
{Show Arr.1} %% output: 3</syntaxhighlight> |
||
There are also [http://www.mozart-oz.org/home/doc/base/tuple.html tuples] (records with consecutive integer keys starting with 1), [http://www.mozart-oz.org/documentation/base/weakdictionary.html weak dictionaries], [http://www.mozart-oz.org/documentation/mozart-stdlib/adt/queue.html queues] and [http://www.mozart-oz.org/documentation/mozart-stdlib/adt/stack.html stacks]. |
There are also [http://www.mozart-oz.org/home/doc/base/tuple.html tuples] (records with consecutive integer keys starting with 1), [http://www.mozart-oz.org/documentation/base/weakdictionary.html weak dictionaries], [http://www.mozart-oz.org/documentation/mozart-stdlib/adt/queue.html queues] and [http://www.mozart-oz.org/documentation/mozart-stdlib/adt/stack.html stacks]. |
||
Line 2,769: | Line 2,769: | ||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Pari has vectors, column vectors, matrices, sets, lists, small vectors, and maps. |
Pari has vectors, column vectors, matrices, sets, lists, small vectors, and maps. |
||
< |
<syntaxhighlight lang="parigp">v = vector(0); |
||
v = []; |
v = []; |
||
cv = vectorv(0); |
cv = vectorv(0); |
||
Line 2,777: | Line 2,777: | ||
l = List(v); |
l = List(v); |
||
vs = vectorsmall(0); |
vs = vectorsmall(0); |
||
M = Map()</ |
M = Map()</syntaxhighlight> |
||
Adding members: |
Adding members: |
||
< |
<syntaxhighlight lang="parigp">listput(l, "hello world") |
||
v=concat(v, [1,2,3]); |
v=concat(v, [1,2,3]); |
||
v=concat(v, 4); |
v=concat(v, 4); |
||
mapput(M, "key", "value");</ |
mapput(M, "key", "value");</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
Different implementations of Pascal have various containers. |
Different implementations of Pascal have various containers. |
||
===Array === |
===Array === |
||
<syntaxhighlight lang="pascal">var |
|||
<lang Pascal>var |
|||
MyArray: array[1..5] of real; |
MyArray: array[1..5] of real; |
||
begin |
begin |
||
MyArray[1] := 4.35; |
MyArray[1] := 4.35; |
||
end;</ |
end;</syntaxhighlight> |
||
===Dynamic Array === |
===Dynamic Array === |
||
<syntaxhighlight lang="pascal">var |
|||
<lang Pascal>var |
|||
MyArray: array of integer; |
MyArray: array of integer; |
||
begin |
begin |
||
setlength (MyArray, 10); |
setlength (MyArray, 10); |
||
MyArray[4] := 99; |
MyArray[4] := 99; |
||
end;</ |
end;</syntaxhighlight> |
||
===Record === |
===Record === |
||
<syntaxhighlight lang="pascal">var |
|||
<lang Pascal>var |
|||
MyRecord: record |
MyRecord: record |
||
x, y, z: real; |
x, y, z: real; |
||
Line 2,810: | Line 2,810: | ||
MyRecord.z := -4.0; |
MyRecord.z := -4.0; |
||
MyRecord.presence := true; |
MyRecord.presence := true; |
||
end;</ |
end;</syntaxhighlight> |
||
===Set === |
===Set === |
||
<syntaxhighlight lang="pascal">type |
|||
<lang Pascal>type |
|||
days = (Mon, Tue, Wed, Thu, Fri, Sat, Sun); |
days = (Mon, Tue, Wed, Thu, Fri, Sat, Sun); |
||
var |
var |
||
Line 2,821: | Line 2,821: | ||
week := workdays + [Sat, Sun]; |
week := workdays + [Sat, Sun]; |
||
weekendDays := week - workdays; |
weekendDays := week - workdays; |
||
end;</ |
end;</syntaxhighlight> |
||
===String === |
===String === |
||
<syntaxhighlight lang="pascal">var |
|||
<lang Pascal>var |
|||
MyString: String; |
MyString: String; |
||
begin |
begin |
||
MyString:= 'Some Text'; |
MyString:= 'Some Text'; |
||
end;</ |
end;</syntaxhighlight> |
||
===List === |
===List === |
||
{{works with|Free_Pascal}} |
{{works with|Free_Pascal}} |
||
{{libheader|Classes}} |
{{libheader|Classes}} |
||
< |
<syntaxhighlight lang="pascal">program ListDemo; |
||
uses |
uses |
||
classes; |
classes; |
||
Line 2,850: | Line 2,850: | ||
writeln (integer(MyList.Items[i]^)); |
writeln (integer(MyList.Items[i]^)); |
||
MyList.Destroy; |
MyList.Destroy; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,862: | Line 2,862: | ||
{{works with|Free_Pascal}} |
{{works with|Free_Pascal}} |
||
{{libheader|Objects}} |
{{libheader|Objects}} |
||
< |
<syntaxhighlight lang="pascal">Program ex34; |
||
{ Program to demonstrate the TCollection.AtInsert method } |
{ Program to demonstrate the TCollection.AtInsert method } |
||
Line 2,895: | Line 2,895: | ||
C^.Foreach(@PrintField); |
C^.Foreach(@PrintField); |
||
Dispose(C, Done); |
Dispose(C, Done); |
||
end.</ |
end.</syntaxhighlight> |
||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Perl has ''array'' and ''hashes''. |
Perl has ''array'' and ''hashes''. |
||
< |
<syntaxhighlight lang="perl">use strict; |
||
my @c = (); # create an empty "array" collection |
my @c = (); # create an empty "array" collection |
||
Line 2,917: | Line 2,917: | ||
foreach my $i ( keys %h ) { |
foreach my $i ( keys %h ) { |
||
print $i . " -> " . $h{$i} . "\n"; |
print $i . " -> " . $h{$i} . "\n"; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Collections can simply be stored as sequences |
Collections can simply be stored as sequences |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">collection</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> |
<span style="color: #004080;">sequence</span> <span style="color: #000000;">collection</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span> |
||
Line 2,927: | Line 2,927: | ||
<span style="color: #000000;">collection</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">collection</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> |
<span style="color: #000000;">collection</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">prepend</span><span style="color: #0000FF;">(</span><span style="color: #000000;">collection</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span> |
||
<span style="color: #0000FF;">?</span> <span style="color: #000000;">collection</span> <span style="color: #000080;font-style:italic;">-- {2,"one"}</span> |
<span style="color: #0000FF;">?</span> <span style="color: #000000;">collection</span> <span style="color: #000080;font-style:italic;">-- {2,"one"}</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
If you want uniqueness, you could simply use a dictionary with values of 0: |
If you want uniqueness, you could simply use a dictionary with values of 0: |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> |
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"one"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> |
||
Line 2,938: | Line 2,938: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
||
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"visitor"</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- shows 2, "one"</span> |
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"visitor"</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- shows 2, "one"</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
PHP has ''associative arrays'' as collection |
PHP has ''associative arrays'' as collection |
||
< |
<syntaxhighlight lang="php"><?php |
||
$a = array(); |
$a = array(); |
||
# add elements "at the end" |
# add elements "at the end" |
||
Line 2,952: | Line 2,952: | ||
$a['two'] = 2; |
$a['two'] = 2; |
||
print_r($a); |
print_r($a); |
||
?></ |
?></syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,972: | Line 2,972: | ||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
===Lists=== |
===Lists=== |
||
< |
<syntaxhighlight lang="picat">go => |
||
L = [1,2,3,4], |
L = [1,2,3,4], |
||
L2 = L ++ [[5,6,7]], % adding a list |
L2 = L ++ [[5,6,7]], % adding a list |
||
Line 2,978: | Line 2,978: | ||
% Prolog way |
% Prolog way |
||
append([0],L,[5],L4).</ |
append([0],L,[5],L4).</syntaxhighlight> |
||
===Arrays=== |
===Arrays=== |
||
Array are often used instead of lists for speed. The array literal use <code>{...}</code> (instead of the lists <code>[...]</code>). |
Array are often used instead of lists for speed. The array literal use <code>{...}</code> (instead of the lists <code>[...]</code>). |
||
< |
<syntaxhighlight lang="picat">go2 => |
||
L = {1,2,3,4}, |
L = {1,2,3,4}, |
||
L2 = {0} ++ L ++ {5}, |
L2 = {0} ++ L ++ {5}, |
||
Line 2,988: | Line 2,988: | ||
% multi dimensional arrays |
% multi dimensional arrays |
||
M = new_array(4,4), |
M = new_array(4,4), |
||
bind_vars(M,0). % initialize to 0</ |
bind_vars(M,0). % initialize to 0</syntaxhighlight> |
||
===Maps=== |
===Maps=== |
||
Associative arrays/Dictionaries. |
Associative arrays/Dictionaries. |
||
< |
<syntaxhighlight lang="picat">go3 => |
||
Map = new_map(), |
Map = new_map(), |
||
Map.put(a,1), |
Map.put(a,1), |
||
Line 2,998: | Line 2,998: | ||
% Initialize map with values |
% Initialize map with values |
||
Map2 = new_map([c=3,d="some value"]).</ |
Map2 = new_map([c=3,d="some value"]).</syntaxhighlight> |
||
===Sets=== |
===Sets=== |
||
A set is a map where every key is associated with the atom 'not_a_value'. All of the built-ins for maps can be applied to sets. |
A set is a map where every key is associated with the atom 'not_a_value'. All of the built-ins for maps can be applied to sets. |
||
< |
<syntaxhighlight lang="picat">go4 => |
||
S = new_set([1,2,3,4,5,"picat"]), |
S = new_set([1,2,3,4,5,"picat"]), |
||
S.put(1), |
S.put(1), |
||
S.put(21).</ |
S.put(21).</syntaxhighlight> |
||
===Structures=== |
===Structures=== |
||
A structure takes the form <code>$s(t1,...,tn)</code>, where <code>s</code> is an atom, and n is called the arity of the |
A structure takes the form <code>$s(t1,...,tn)</code>, where <code>s</code> is an atom, and n is called the arity of the |
||
structure. The dollar symbol is used to distinguish a structure from a function call. |
structure. The dollar symbol is used to distinguish a structure from a function call. |
||
< |
<syntaxhighlight lang="picat">go5 => |
||
S = new_struct(a_struct,5), |
S = new_struct(a_struct,5), |
||
S[2] = 4, % place 4 at position 2 |
S[2] = 4, % place 4 at position 2 |
||
arg(3,S,"string"). % place "string" at position 3</ |
arg(3,S,"string"). % place "string" at position 3</syntaxhighlight> |
||
===Heaps=== |
===Heaps=== |
||
A heap is a complete binary tree represented as an array. A heap can be a min-heap or a max-heap. In a min-heap, the value at the root of each subtree is the minimum among all the values in the subtree. In a max-heap, the value at the root of each subtree is the maximum among all the values in the subtree. |
A heap is a complete binary tree represented as an array. A heap can be a min-heap or a max-heap. In a min-heap, the value at the root of each subtree is the minimum among all the values in the subtree. In a max-heap, the value at the root of each subtree is the maximum among all the values in the subtree. |
||
< |
<syntaxhighlight lang="picat">go6 => |
||
L = [1,3,2,4,5,3,6], |
L = [1,3,2,4,5,3,6], |
||
H = new_min_heap(L), |
H = new_min_heap(L), |
||
H.heap_push(-123).</ |
H.heap_push(-123).</syntaxhighlight> |
||
Line 3,027: | Line 3,027: | ||
[http://software-lab.de/doc/refI.html#idx index] trees or |
[http://software-lab.de/doc/refI.html#idx index] trees or |
||
[http://software-lab.de/doc/ref.html#symbol property] lists). |
[http://software-lab.de/doc/ref.html#symbol property] lists). |
||
< |
<syntaxhighlight lang="picolisp">: (setq Lst (3 4 5 6)) |
||
-> (3 4 5 6) |
-> (3 4 5 6) |
||
Line 3,040: | Line 3,040: | ||
: (insert 4 Lst 'X) |
: (insert 4 Lst 'X) |
||
-> (1 2 3 X 4 5 6)</ |
-> (1 2 3 X 4 5 6)</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
declare countries character (20) varying controlled; |
declare countries character (20) varying controlled; |
||
allocate countries initial ('Britain'); |
allocate countries initial ('Britain'); |
||
allocate countries initial ('America'); |
allocate countries initial ('America'); |
||
allocate countries initial ('Argentina'); |
allocate countries initial ('Argentina'); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
Line 3,054: | Line 3,054: | ||
===Array=== |
===Array=== |
||
The array index is zero based. |
The array index is zero based. |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
# Create an Array by separating the elements with commas: |
# Create an Array by separating the elements with commas: |
||
$array = "one", 2, "three", 4 |
$array = "one", 2, "three", 4 |
||
Line 3,102: | Line 3,102: | ||
$multiArray[2,2] # returns 33 |
$multiArray[2,2] # returns 33 |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Hash Table=== |
===Hash Table=== |
||
Hash tables come in two varieties: normal and ordered, where of course, the order of entry is retained. |
Hash tables come in two varieties: normal and ordered, where of course, the order of entry is retained. |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
# An empty Hash Table: |
# An empty Hash Table: |
||
$hash = @{} |
$hash = @{} |
||
Line 3,152: | Line 3,152: | ||
Vikings = "Minnesota" |
Vikings = "Minnesota" |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Other Collection Types=== |
===Other Collection Types=== |
||
PowerShell is a .NET language so '''all''' of the collection types in .NET are available to PowerShell. The most commonly used would probably be <code>[System.Collections.ArrayList]</code>. |
PowerShell is a .NET language so '''all''' of the collection types in .NET are available to PowerShell. The most commonly used would probably be <code>[System.Collections.ArrayList]</code>. |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
$list = New-Object -TypeName System.Collections.ArrayList -ArgumentList 1,2,3 |
$list = New-Object -TypeName System.Collections.ArrayList -ArgumentList 1,2,3 |
||
Line 3,165: | Line 3,165: | ||
$list.Add(4) | Out-Null |
$list.Add(4) | Out-Null |
||
$list.RemoveAt(2) |
$list.RemoveAt(2) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Prolog}}== |
=={{header|Prolog}}== |
||
Traditionally Prolog supports only lists. |
Traditionally Prolog supports only lists. |
||
< |
<syntaxhighlight lang="prolog">% create a list |
||
L = [a,b,c,d], |
L = [a,b,c,d], |
||
Line 3,179: | Line 3,179: | ||
% delete from list |
% delete from list |
||
exclude(=(b), L3, L4).</ |
exclude(=(b), L3, L4).</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,190: | Line 3,190: | ||
SWI-Prolog supports some other collection types as built in libraries, the most notable is the Dict. |
SWI-Prolog supports some other collection types as built in libraries, the most notable is the Dict. |
||
Dicts can be accessed using a special notation and can be added and removed from in an immutable way. |
Dicts can be accessed using a special notation and can be added and removed from in an immutable way. |
||
< |
<syntaxhighlight lang="prolog">% create an empty dict call 'point' |
||
D1 = point{}, |
D1 = point{}, |
||
Line 3,203: | Line 3,203: | ||
% access a value randomly |
% access a value randomly |
||
format('x = ~w, y = ~w~n', [D4.x, D4.y]).</ |
format('x = ~w, y = ~w~n', [D4.x, D4.y]).</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,216: | Line 3,216: | ||
===Arrays=== |
===Arrays=== |
||
Creating an [http://www.purebasic.com/documentation/array/index.html Array] of 10 strings (could be any type). PureBasic starts the index with element 0. |
Creating an [http://www.purebasic.com/documentation/array/index.html Array] of 10 strings (could be any type). PureBasic starts the index with element 0. |
||
< |
<syntaxhighlight lang="purebasic">Dim Text.s(9) |
||
Text(3)="Hello" |
Text(3)="Hello" |
||
Text(7)="World!"</ |
Text(7)="World!"</syntaxhighlight> |
||
===Linked Lists=== |
===Linked Lists=== |
||
Create a [http://www.purebasic.com/documentation/linkedlist/index.html Linked List] for strings (could be any type), then add two elements. |
Create a [http://www.purebasic.com/documentation/linkedlist/index.html Linked List] for strings (could be any type), then add two elements. |
||
< |
<syntaxhighlight lang="purebasic">NewList Cars.s() |
||
AddElement(Cars()): Cars()="Volvo" |
AddElement(Cars()): Cars()="Volvo" |
||
AddElement(Cars()): Cars()="BMV"</ |
AddElement(Cars()): Cars()="BMV"</syntaxhighlight> |
||
===Hash table=== |
===Hash table=== |
||
Create a [http://www.purebasic.com/documentation/map/index.html Map], e.g. a hash table that could be any type. The size of the dictionary can be defined as needed, otherwise a default value is used. |
Create a [http://www.purebasic.com/documentation/map/index.html Map], e.g. a hash table that could be any type. The size of the dictionary can be defined as needed, otherwise a default value is used. |
||
< |
<syntaxhighlight lang="purebasic">NewMap Capitals.s() |
||
Capitals("USA") = "Washington" |
Capitals("USA") = "Washington" |
||
Capitals("Sweden")= "Stockholm"</ |
Capitals("Sweden")= "Stockholm"</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
{{works with|Python|2.5}} |
{{works with|Python|2.5}} |
||
Python supports lists, tuples, dictionaries and now sets as built-in collection types. See http://docs.python.org/tut/node7.html for further details. |
Python supports lists, tuples, dictionaries and now sets as built-in collection types. See http://docs.python.org/tut/node7.html for further details. |
||
< |
<syntaxhighlight lang="python">collection = [0, '1'] # Lists are mutable (editable) and can be sorted in place |
||
x = collection[0] # accessing an item (which happens to be a numeric 0 (zero) |
x = collection[0] # accessing an item (which happens to be a numeric 0 (zero) |
||
collection.append(2) # adding something to the end of the list |
collection.append(2) # adding something to the end of the list |
||
Line 3,257: | Line 3,257: | ||
collection = {0: "zero", 1: "one"} # Dictionaries (Hash) |
collection = {0: "zero", 1: "one"} # Dictionaries (Hash) |
||
collection['zero'] = 2 # Dictionary members accessed using same syntax as list/array indexes. |
collection['zero'] = 2 # Dictionary members accessed using same syntax as list/array indexes. |
||
collection = set([0, '1']) # sets (Hash)</ |
collection = set([0, '1']) # sets (Hash)</syntaxhighlight> |
||
In addition Python classes support a number of methods allowing them to implement indexing, slicing, and attribute management features as collections. Thus many modules in the Python standard libraries allow one to treat files contents, databases, and other data using the same syntax as the native collection types. Some Python modules (such as Numeric and NumPy) provide low-level implementations of additional collections (such as efficient n-dimensional arrays). |
In addition Python classes support a number of methods allowing them to implement indexing, slicing, and attribute management features as collections. Thus many modules in the Python standard libraries allow one to treat files contents, databases, and other data using the same syntax as the native collection types. Some Python modules (such as Numeric and NumPy) provide low-level implementations of additional collections (such as efficient n-dimensional arrays). |
||
Line 3,265: | Line 3,265: | ||
===Vectors=== |
===Vectors=== |
||
Numeric (floating point) |
Numeric (floating point) |
||
< |
<syntaxhighlight lang="r">numeric(5) |
||
1:10 |
1:10 |
||
c(1, 3, 6, 10, 7 + 8, sqrt(441))</ |
c(1, 3, 6, 10, 7 + 8, sqrt(441))</syntaxhighlight> |
||
[1] 0 0 0 0 0 |
[1] 0 0 0 0 0 |
||
[1] 1 2 3 4 5 6 7 8 9 10 |
[1] 1 2 3 4 5 6 7 8 9 10 |
||
[1] 1 3 6 10 15 21 |
[1] 1 3 6 10 15 21 |
||
Integer |
Integer |
||
< |
<syntaxhighlight lang="r">integer(5) |
||
c(1L, -2L, 99L);</ |
c(1L, -2L, 99L);</syntaxhighlight> |
||
[1] 0 0 0 0 0 |
[1] 0 0 0 0 0 |
||
[1] 1 -2 99 |
[1] 1 -2 99 |
||
Logical |
Logical |
||
< |
<syntaxhighlight lang="r">logical(5) |
||
c(TRUE, FALSE)</ |
c(TRUE, FALSE)</syntaxhighlight> |
||
[1] FALSE FALSE FALSE FALSE FALSE |
[1] FALSE FALSE FALSE FALSE FALSE |
||
[1] TRUE FALSE |
[1] TRUE FALSE |
||
Character |
Character |
||
< |
<syntaxhighlight lang="r">character(5) |
||
c("abc", "defg", "")</ |
c("abc", "defg", "")</syntaxhighlight> |
||
[1] "" "" "" "" "" |
[1] "" "" "" "" "" |
||
[1] "abc" "defg" "" |
[1] "abc" "defg" "" |
||
===Arrays and Matrices=== |
===Arrays and Matrices=== |
||
These are essentially vectors with a dimension attribute. Matrices are just arrays with two dimensions (and a different class). |
These are essentially vectors with a dimension attribute. Matrices are just arrays with two dimensions (and a different class). |
||
< |
<syntaxhighlight lang="r">matrix(1:12, nrow=3) |
||
array(1:24, dim=c(2,3,4)) #output not shown</ |
array(1:24, dim=c(2,3,4)) #output not shown</syntaxhighlight> |
||
[,1] [,2] [,3] [,4] |
[,1] [,2] [,3] [,4] |
||
[1,] 1 4 7 10 |
[1,] 1 4 7 10 |
||
Line 3,297: | Line 3,297: | ||
===Lists=== |
===Lists=== |
||
Lists are collections of other variables (that can include other lists). |
Lists are collections of other variables (that can include other lists). |
||
< |
<syntaxhighlight lang="r">list(a=123, b="abc", TRUE, 1:5, c=list(d=runif(5), e=5+6))</syntaxhighlight> |
||
< |
<syntaxhighlight lang="r">$a |
||
[1] 123 |
[1] 123 |
||
$b |
$b |
||
Line 3,310: | Line 3,310: | ||
[1] 0.6013157 0.5011909 0.7106448 0.3882265 0.1274939 |
[1] 0.6013157 0.5011909 0.7106448 0.3882265 0.1274939 |
||
$c$e |
$c$e |
||
[1] 11</ |
[1] 11</syntaxhighlight> |
||
===Data Frames=== |
===Data Frames=== |
||
Data frames are like a cross between a list and a matrix. Each row represents one "record", or a collection of variables. |
Data frames are like a cross between a list and a matrix. Each row represents one "record", or a collection of variables. |
||
< |
<syntaxhighlight lang="r">data.frame(name=c("Alice", "Bob", "Carol"), age=c(23, 35, 17))</syntaxhighlight> |
||
name age |
name age |
||
1 Alice 23 |
1 Alice 23 |
||
Line 3,322: | Line 3,322: | ||
As in other lisps, the simple kind of linked lists are the most common collection-of-values type. |
As in other lisps, the simple kind of linked lists are the most common collection-of-values type. |
||
<syntaxhighlight lang="racket"> |
|||
<lang Racket> |
|||
#lang racket |
#lang racket |
||
Line 3,331: | Line 3,331: | ||
;; add an element to the front of a list (non-destructively) |
;; add an element to the front of a list (non-destructively) |
||
(cons 1 (list 2 3 4)) |
(cons 1 (list 2 3 4)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Racket comes with about 7000 additional types that can be considered as a collection of values, but it's not clear whether this entry is supposed to be a laundry list... |
Racket comes with about 7000 additional types that can be considered as a collection of values, but it's not clear whether this entry is supposed to be a laundry list... |
||
Line 3,339: | Line 3,339: | ||
Raku has both mutable and immutable containers of various sorts. Here are some of the most common ones: |
Raku has both mutable and immutable containers of various sorts. Here are some of the most common ones: |
||
===Mutable=== |
===Mutable=== |
||
<lang |
<syntaxhighlight lang="raku" line># Array |
||
my @array = 1,2,3; |
my @array = 1,2,3; |
||
@array.push: 4,5,6; |
@array.push: 4,5,6; |
||
Line 3,354: | Line 3,354: | ||
# BagHash |
# BagHash |
||
my $b = BagHash.new: <b a k l a v a>; |
my $b = BagHash.new: <b a k l a v a>; |
||
$b ⊎= <a b c>;</ |
$b ⊎= <a b c>;</syntaxhighlight> |
||
===Immutable=== |
===Immutable=== |
||
<lang |
<syntaxhighlight lang="raku" line># List |
||
my @list := 1,2,3; |
my @list := 1,2,3; |
||
my @newlist := |@list, 4,5,6; # |@list will slip @list into the surrounding list instead of creating a list of lists |
my @newlist := |@list, 4,5,6; # |@list will slip @list into the surrounding list instead of creating a list of lists |
||
Line 3,367: | Line 3,367: | ||
# Bag |
# Bag |
||
my $bag = bag <b a k l a v a>; |
my $bag = bag <b a k l a v a>; |
||
my $newbag = $bag ⊎ <b e e f>;</ |
my $newbag = $bag ⊎ <b e e f>;</syntaxhighlight> |
||
===Pair list (cons list)=== |
===Pair list (cons list)=== |
||
<lang |
<syntaxhighlight lang="raku" line>my $tail = d => e => f => Nil; |
||
my $new = a => b => c => $tail;</ |
my $new = a => b => c => $tail;</syntaxhighlight> |
||
===P6opaque object (immutable in structure)=== |
===P6opaque object (immutable in structure)=== |
||
<lang |
<syntaxhighlight lang="raku" line>class Something { has $.foo; has $.bar }; |
||
my $obj = Something.new: foo => 1, bar => 2; |
my $obj = Something.new: foo => 1, bar => 2; |
||
my $newobj = $obj but role { has $.baz = 3 } # anonymous mixin</ |
my $newobj = $obj but role { has $.baz = 3 } # anonymous mixin</syntaxhighlight> |
||
=={{header|Raven}}== |
=={{header|Raven}}== |
||
Line 3,382: | Line 3,382: | ||
Numerically indexed List: |
Numerically indexed List: |
||
< |
<syntaxhighlight lang="raven">[ 1 2 3 'abc' ] as a_list |
||
a_list print |
a_list print |
||
Line 3,389: | Line 3,389: | ||
1 => 2 |
1 => 2 |
||
2 => 3 |
2 => 3 |
||
3 => "abc"</ |
3 => "abc"</syntaxhighlight> |
||
String key indexed Hash: |
String key indexed Hash: |
||
< |
<syntaxhighlight lang="raven">{ 'a' 1 'b' 2 } as a_hash |
||
a_hash print |
a_hash print |
||
hash (2 items) |
hash (2 items) |
||
a => 1 |
a => 1 |
||
b => 2</ |
b => 2</syntaxhighlight> |
||
Set items: |
Set items: |
||
< |
<syntaxhighlight lang="raven">17 a_list 1 set # set second item |
||
42 a_hash 'b' set # set item with key 'b' |
42 a_hash 'b' set # set item with key 'b' |
||
42 a_hash:b # shorthand</ |
42 a_hash:b # shorthand</syntaxhighlight> |
||
Get items: |
Get items: |
||
< |
<syntaxhighlight lang="raven">a_list 1 get # get second item |
||
a_hash 'b' get # get item with key 'b' |
a_hash 'b' get # get item with key 'b' |
||
a_hash.b # shorthand</ |
a_hash.b # shorthand</syntaxhighlight> |
||
Other stuff: |
Other stuff: |
||
< |
<syntaxhighlight lang="raven">42 a_list push # append an item |
||
a_list pop # remove last item |
a_list pop # remove last item |
||
42 a_list shove # prepend an item |
42 a_list shove # prepend an item |
||
a_list shift # remove first item |
a_list shift # remove first item |
||
42 a_list 1 insert # insert item second, shuffling others down |
42 a_list 1 insert # insert item second, shuffling others down |
||
a_list 1 remove # retrieve second item, shuffling others up</ |
a_list 1 remove # retrieve second item, shuffling others up</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 3,435: | Line 3,435: | ||
To store (say) a collection of numbers (or anything, |
To store (say) a collection of numbers (or anything, |
||
for that matter) into a stemmed array: |
for that matter) into a stemmed array: |
||
< |
<syntaxhighlight lang="rexx">pr. = /*define a default for all elements for the array*/ |
||
pr.1 = 2 /*note that this array starts at 1 (one). */ |
pr.1 = 2 /*note that this array starts at 1 (one). */ |
||
Line 3,472: | Line 3,472: | ||
do n=-5 to 5 /*define a stemmed array from -5 to 5 */ |
do n=-5 to 5 /*define a stemmed array from -5 to 5 */ |
||
sawtooth.n = n /*the sawtooth array is, well, a sawtooth curve*/ |
sawtooth.n = n /*the sawtooth array is, well, a sawtooth curve*/ |
||
end /*n*/ /*note that eleven elements will be defined. */</ |
end /*n*/ /*note that eleven elements will be defined. */</syntaxhighlight> |
||
Most often, programmers will assign the zero entry to the |
Most often, programmers will assign the zero entry to the |
||
number of elements in the stemmed array. |
number of elements in the stemmed array. |
||
Line 3,478: | Line 3,478: | ||
This means that any index of the stemmed array must be positive to be useful for |
This means that any index of the stemmed array must be positive to be useful for |
||
storing numbers. |
storing numbers. |
||
< |
<syntaxhighlight lang="rexx"> pr.0= 15 /*number of (data) entries in the stemmed array. */</syntaxhighlight> |
||
Programmatically, a simple test could be performed to detect the |
Programmatically, a simple test could be performed to detect the |
||
end of the array (if there aren't any ''null'' values): |
end of the array (if there aren't any ''null'' values): |
||
< |
<syntaxhighlight lang="rexx"> do j=1 while pr.j\=='' |
||
say 'prime' j "is" pr.j |
say 'prime' j "is" pr.j |
||
end /*j*/ |
end /*j*/ |
||
/*at this point, J=16 (because of the DO */ |
/*at this point, J=16 (because of the DO */ |
||
/*loop incrementing the index. */ |
/*loop incrementing the index. */ |
||
j= j-1 /*J now has the count of primes stored. */</ |
j= j-1 /*J now has the count of primes stored. */</syntaxhighlight> |
||
===lists or vectors=== |
===lists or vectors=== |
||
To store (say) a collection of numbers (or anything, for that matter) into a list: |
To store (say) a collection of numbers (or anything, for that matter) into a list: |
||
< |
<syntaxhighlight lang="rexx">primeList = '2 3 5 7 11 13 17 19 23 29 31 37 41 43' /* or ··· */ |
||
primeList = 2 3 5 7 11 13 17 19 23 29 31 37 41 43 |
primeList = 2 3 5 7 11 13 17 19 23 29 31 37 41 43 |
||
Line 3,504: | Line 3,504: | ||
/*very efficient for very large arrays (those */ |
/*very efficient for very large arrays (those */ |
||
/*with many many thousands of elements). */ |
/*with many many thousands of elements). */ |
||
end /*j*/</ |
end /*j*/</syntaxhighlight> |
||
The use of lists (in the above manner) is suitable for words (or numbers) that do not have |
The use of lists (in the above manner) is suitable for words (or numbers) that do not have |
||
leading, embedded, or |
leading, embedded, or |
||
Line 3,516: | Line 3,516: | ||
To store (for instance) a collection of numbers (or anything, for that matter) into |
To store (for instance) a collection of numbers (or anything, for that matter) into |
||
a sparse stemmed array: |
a sparse stemmed array: |
||
< |
<syntaxhighlight lang="rexx">pr. = 0 /*define a default for all elements for the array.*/ |
||
pr.2 = 1 |
pr.2 = 1 |
||
pr.3 = 1 |
pr.3 = 1 |
||
Line 3,565: | Line 3,565: | ||
end /*k*/ |
end /*k*/ |
||
say 'The number of primes found in the list is: ' #</ |
say 'The number of primes found in the list is: ' #</syntaxhighlight><br><br> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
text = list(2) |
text = list(2) |
||
text[1] = "Hello " |
text[1] = "Hello " |
||
text[2] = "world!" |
text[2] = "world!" |
||
see text[1] + text[2] + nl |
see text[1] + text[2] + nl |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 3,583: | Line 3,583: | ||
===Array=== |
===Array=== |
||
Arrays are ordered, integer-indexed collections of any object. |
Arrays are ordered, integer-indexed collections of any object. |
||
< |
<syntaxhighlight lang="ruby"># creating an empty array and adding values |
||
a = [] #=> [] |
a = [] #=> [] |
||
a[0] = 1 #=> [1] |
a[0] = 1 #=> [1] |
||
Line 3,593: | Line 3,593: | ||
a = Array.new(3) #=> [nil, nil, nil] |
a = Array.new(3) #=> [nil, nil, nil] |
||
a = Array.new(3, 0) #=> [0, 0, 0] |
a = Array.new(3, 0) #=> [0, 0, 0] |
||
a = Array.new(3){|i| i*2} #=> [0, 2, 4]</ |
a = Array.new(3){|i| i*2} #=> [0, 2, 4]</syntaxhighlight> |
||
===Hash=== |
===Hash=== |
||
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. |
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. |
||
< |
<syntaxhighlight lang="ruby"># creating an empty hash |
||
h = {} #=> {} |
h = {} #=> {} |
||
h["a"] = 1 #=> {"a"=>1} |
h["a"] = 1 #=> {"a"=>1} |
||
Line 3,618: | Line 3,618: | ||
#=> {} |
#=> {} |
||
p h[1] #=> "foo1" |
p h[1] #=> "foo1" |
||
p h #=> {1=>"foo1"}</ |
p h #=> {1=>"foo1"}</syntaxhighlight> |
||
===Struct=== |
===Struct=== |
||
A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class. |
A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class. |
||
< |
<syntaxhighlight lang="ruby"># creating a struct |
||
Person = Struct.new(:name, :age, :sex) |
Person = Struct.new(:name, :age, :sex) |
||
Line 3,643: | Line 3,643: | ||
c = Person["Daniel", 22, :Man] |
c = Person["Daniel", 22, :Man] |
||
p c.to_h #=> {:name=>"Daniel", :age=>22, :sex=>:Man}</ |
p c.to_h #=> {:name=>"Daniel", :age=>22, :sex=>:Man}</syntaxhighlight> |
||
===Set=== |
===Set=== |
||
Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup. |
Set implements a collection of unordered values with no duplicates. This is a hybrid of Array's intuitive inter-operation facilities and Hash's fast lookup. |
||
< |
<syntaxhighlight lang="ruby">require 'set' |
||
# different ways of creating a set |
# different ways of creating a set |
||
Line 3,668: | Line 3,668: | ||
p s1.add(5) #=> #<Set: {1, 2, 3, 4, 5}> |
p s1.add(5) #=> #<Set: {1, 2, 3, 4, 5}> |
||
p s1 << 0 #=> #<Set: {1, 2, 3, 4, 5, 0}> |
p s1 << 0 #=> #<Set: {1, 2, 3, 4, 5, 0}> |
||
p s1.delete(3) #=> #<Set: {1, 2, 4, 5, 0}></ |
p s1.delete(3) #=> #<Set: {1, 2, 4, 5, 0}></syntaxhighlight> |
||
===Matrix and Vector=== |
===Matrix and Vector=== |
||
The Matrix and Vector class represents a mathematical matrix and vector. |
The Matrix and Vector class represents a mathematical matrix and vector. |
||
< |
<syntaxhighlight lang="ruby">require 'matrix' |
||
# creating a matrix |
# creating a matrix |
||
Line 3,695: | Line 3,695: | ||
p m1 * v1 #=> Vector[1, 3, 5] |
p m1 * v1 #=> Vector[1, 3, 5] |
||
p m3 * v1 #=> Vector[-13, -4, 5]</ |
p m3 * v1 #=> Vector[-13, -4, 5]</syntaxhighlight> |
||
===OpenStruct=== |
===OpenStruct=== |
||
An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values. |
An OpenStruct is a data structure, similar to a Hash, that allows the definition of arbitrary attributes with their accompanying values. |
||
< |
<syntaxhighlight lang="ruby">require 'ostruct' |
||
# creating a OpenStruct |
# creating a OpenStruct |
||
Line 3,721: | Line 3,721: | ||
son.items = ["candy","toy"] |
son.items = ["candy","toy"] |
||
p son.items #=> ["candy","toy"] |
p son.items #=> ["candy","toy"] |
||
p son #=> #<OpenStruct name="Thomas", age=4, items=["candy", "toy"]</ |
p son #=> #<OpenStruct name="Thomas", age=4, items=["candy", "toy"]</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
Line 3,728: | Line 3,728: | ||
====Array==== |
====Array==== |
||
Arrays (<code>[T]</code>) are stack allocated, fixed size collections of items of the same type. |
Arrays (<code>[T]</code>) are stack allocated, fixed size collections of items of the same type. |
||
< |
<syntaxhighlight lang="rust">let a = [1u8,2,3,4,5]; // a is of type [u8; 5]; |
||
let b = [0;256] // Equivalent to `let b = [0,0,0,0,0,0... repeat 256 times]`</ |
let b = [0;256] // Equivalent to `let b = [0,0,0,0,0,0... repeat 256 times]`</syntaxhighlight> |
||
====Slice==== |
====Slice==== |
||
Slices (<code>&[T]</code>) are dynamically sized views into contiguous sequences (arrays, vectors, strings) |
Slices (<code>&[T]</code>) are dynamically sized views into contiguous sequences (arrays, vectors, strings) |
||
< |
<syntaxhighlight lang="rust">let array = [1,2,3,4,5]; |
||
let slice = &array[0..2] |
let slice = &array[0..2] |
||
println!("{:?}", slice);</ |
println!("{:?}", slice);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1,2]</pre> |
<pre>[1,2]</pre> |
||
Line 3,750: | Line 3,750: | ||
* You want a heap-allocated array. |
* You want a heap-allocated array. |
||
< |
<syntaxhighlight lang="rust">let mut v = Vec::new(); |
||
v.push(1); |
v.push(1); |
||
v.push(2); |
v.push(2); |
||
v.push(3); |
v.push(3); |
||
// Or (mostly) equivalently via a convenient macro in the standard library |
// Or (mostly) equivalently via a convenient macro in the standard library |
||
let v = vec![1,2,3];</ |
let v = vec![1,2,3];</syntaxhighlight> |
||
====String==== |
====String==== |
||
<code>String</code>s are growable strings stored as a UTF-8 buffer which are just <code>Vec<u8></code>s under the hood. Like <code>str</code>s, they are not indexable (for the same reasons) but iterators can be created over the graphemes, codepoints or bytes therein. |
<code>String</code>s are growable strings stored as a UTF-8 buffer which are just <code>Vec<u8></code>s under the hood. Like <code>str</code>s, they are not indexable (for the same reasons) but iterators can be created over the graphemes, codepoints or bytes therein. |
||
< |
<syntaxhighlight lang="rust">let x = "abc"; // x is of type &str (a borrowed string slice) |
||
let s = String::from(x); |
let s = String::from(x); |
||
// or alternatively |
// or alternatively |
||
let s = x.to_owned();</ |
let s = x.to_owned();</syntaxhighlight> |
||
====VecDequeue==== |
====VecDequeue==== |
||
Line 3,799: | Line 3,799: | ||
The collections are available in two flavors; immutable (these have no methods to modify or update) and mutable. With these properties they are also available in concurrent version for parallel processing. Switching between sequential and parallel can easily be done by adding a .seq or .par post-fix. |
The collections are available in two flavors; immutable (these have no methods to modify or update) and mutable. With these properties they are also available in concurrent version for parallel processing. Switching between sequential and parallel can easily be done by adding a .seq or .par post-fix. |
||
These examples were taken from a Scala REPL session. The second lines are the REPL responces.< |
These examples were taken from a Scala REPL session. The second lines are the REPL responces.<syntaxhighlight lang="scala">Windows PowerShell |
||
Copyright (C) 2012 Microsoft Corporation. All rights reserved. |
Copyright (C) 2012 Microsoft Corporation. All rights reserved. |
||
Line 3,856: | Line 3,856: | ||
res19: queue.type = Queue("first", "second") |
res19: queue.type = Queue("first", "second") |
||
scala></ |
scala></syntaxhighlight> |
||
< |
<syntaxhighlight lang="scala"> import collection.concurrent.TrieMap |
||
// super concurrent mutable hashmap |
// super concurrent mutable hashmap |
||
Line 3,886: | Line 3,886: | ||
map.filter { k => k._1 > 3 } // Map(5 -> 6, 44 -> 99) |
map.filter { k => k._1 > 3 } // Map(5 -> 6, 44 -> 99) |
||
// // same with for syntax |
// // same with for syntax |
||
for ((k, v) <- map; if k > 3) yield (k, v)</ |
for ((k, v) <- map; if k > 3) yield (k, v)</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
===list=== |
===list=== |
||
<lang |
<syntaxhighlight lang="scheme">(list obj ...)</syntaxhighlight> |
||
returns a newly allocated list of its arguments. |
returns a newly allocated list of its arguments. |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="scheme">(display (list 1 2 3)) |
||
(newline) |
(newline) |
||
(display (list)) |
(display (list)) |
||
(newline)</ |
(newline)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(1 2 3) |
<pre>(1 2 3) |
||
Line 3,903: | Line 3,903: | ||
===cons=== |
===cons=== |
||
<lang |
<syntaxhighlight lang="scheme">(cons obj lst)</syntaxhighlight> |
||
returns a newly allocated list consisting of <code>obj</code> prepended to <code>lst</code>. |
returns a newly allocated list consisting of <code>obj</code> prepended to <code>lst</code>. |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="scheme">(display (cons 0 (list 1 2 3))) |
||
(newline)</ |
(newline)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(0 1 2 3)</pre> |
<pre>(0 1 2 3)</pre> |
||
===append=== |
===append=== |
||
<lang |
<syntaxhighlight lang="scheme">(append lst ...)</syntaxhighlight> |
||
returns a newly allocated list consisting of the elements of <code>lst</code> followed by the elements of the other lists. |
returns a newly allocated list consisting of the elements of <code>lst</code> followed by the elements of the other lists. |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="scheme">(display (append (list 1 2 3) (list 4 5 6))) |
||
(newline)</ |
(newline)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>(1 2 3 4 5 6)</pre> |
<pre>(1 2 3 4 5 6)</pre> |
||
Line 3,924: | Line 3,924: | ||
===set=== |
===set=== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
enable_output(set of string); |
enable_output(set of string); |
||
Line 3,935: | Line 3,935: | ||
incl(aSet, "silver"); |
incl(aSet, "silver"); |
||
writeln(aSet); |
writeln(aSet); |
||
end func;</ |
end func;</syntaxhighlight> |
||
===array=== |
===array=== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const proc: main is func |
const proc: main is func |
||
Line 3,954: | Line 3,954: | ||
end for; |
end for; |
||
writeln; |
writeln; |
||
end func;</ |
end func;</syntaxhighlight> |
||
===hash=== |
===hash=== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
const type: aHashType is hash [string] string; |
const type: aHashType is hash [string] string; |
||
Line 3,972: | Line 3,972: | ||
writeln(aKey <& ": " <& aValue); |
writeln(aKey <& ": " <& aValue); |
||
end for;a |
end for;a |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Setl4}}== |
=={{header|Setl4}}== |
||
===Set=== |
===Set=== |
||
< |
<syntaxhighlight lang="setl4"> |
||
set = new('set 5 10 15 20 25 25') |
set = new('set 5 10 15 20 25 25') |
||
add(set,30) |
add(set,30) |
||
Line 3,987: | Line 3,987: | ||
show.eval("exists(set,'eq(this,10)')") |
show.eval("exists(set,'eq(this,10)')") |
||
show.eval("forall(set,'eq(this,40)')") |
show.eval("forall(set,'eq(this,40)')") |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Iter=== |
===Iter=== |
||
< |
<syntaxhighlight lang="setl4"> |
||
iter = new('iter 1 10 2') |
iter = new('iter 1 10 2') |
||
show(iter) |
show(iter) |
||
show.eval("eq(set.size(iter),5)") |
show.eval("eq(set.size(iter),5)") |
||
show.eval('member(iter,5)') |
show.eval('member(iter,5)') |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Map=== |
===Map=== |
||
< |
<syntaxhighlight lang="setl4"> |
||
map = new('map one:1 two:2 ten:10 forty:40 hundred:100 thousand:1000') |
map = new('map one:1 two:2 ten:10 forty:40 hundred:100 thousand:1000') |
||
show(map) |
show(map) |
||
Line 4,004: | Line 4,004: | ||
show.eval("exists(map,'eq(get(map,this),2)')") |
show.eval("exists(map,'eq(get(map,this),2)')") |
||
show.eval("forall(map,'eq(get(map,this),2)')") |
show.eval("forall(map,'eq(get(map,this),2)')") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
===Array=== |
===Array=== |
||
Arrays are ordered, integer-indexed collections of any object. |
Arrays are ordered, integer-indexed collections of any object. |
||
< |
<syntaxhighlight lang="ruby"># creating an empty array and adding values |
||
var a = [] #=> [] |
var a = [] #=> [] |
||
a[0] = 1 #=> [1] |
a[0] = 1 #=> [1] |
||
a[3] = "abc" #=> [1, nil, nil, "abc"] |
a[3] = "abc" #=> [1, nil, nil, "abc"] |
||
a << 3.14 #=> [1, nil, nil, "abc", 3.14]</ |
a << 3.14 #=> [1, nil, nil, "abc", 3.14]</syntaxhighlight> |
||
===Hash=== |
===Hash=== |
||
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type, which is automatically converted into a String. |
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type, which is automatically converted into a String. |
||
< |
<syntaxhighlight lang="ruby"># creating an empty hash |
||
var h = Hash() #=> Hash() |
var h = Hash() #=> Hash() |
||
h{:foo} = 1 #=> Hash("foo"=>1) |
h{:foo} = 1 #=> Hash("foo"=>1) |
||
h{:bar} = 2.4 #=> Hash("foo"=>1, "bar"=>2.4) |
h{:bar} = 2.4 #=> Hash("foo"=>1, "bar"=>2.4) |
||
h{:bar} += 3 #=> Hash("foo"=>1, "bar"=>5.4)</ |
h{:bar} += 3 #=> Hash("foo"=>1, "bar"=>5.4)</syntaxhighlight> |
||
===Pair=== |
===Pair=== |
||
A Pair is an array-like collection, but restricted only to two elements. |
A Pair is an array-like collection, but restricted only to two elements. |
||
< |
<syntaxhighlight lang="ruby"># create a simple pair |
||
var p = Pair('a', 'b') |
var p = Pair('a', 'b') |
||
say p.first; #=> 'a' |
say p.first; #=> 'a' |
||
Line 4,038: | Line 4,038: | ||
pair = pair.second; |
pair = pair.second; |
||
pair == nil && break; |
pair == nil && break; |
||
}</ |
}</syntaxhighlight> |
||
===Struct=== |
===Struct=== |
||
A Struct is a convenient way to bundle a number of attributes together. |
A Struct is a convenient way to bundle a number of attributes together. |
||
< |
<syntaxhighlight lang="ruby"># creating a struct |
||
struct Person { |
struct Person { |
||
String name, |
String name, |
||
Line 4,056: | Line 4,056: | ||
say a.name #=> "Dr. John Smith" |
say a.name #=> "Dr. John Smith" |
||
say a.age #=> 42 |
say a.age #=> 42 |
||
say a.sex #=> "man"</ |
say a.sex #=> "man"</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
< |
<syntaxhighlight lang="slate">{1. 2. 3. 4. 5} collect: [|:x| x + 1]. "--> {2. 3. 4. 5. 6}" |
||
{1. 2. 3. 4. 5} select: #isOdd `er. "--> {1. 3. 5}" |
{1. 2. 3. 4. 5} select: #isOdd `er. "--> {1. 3. 5}" |
||
({3. 2. 7} collect: #+ `er <- 3) sort. "--> {"SortedArray traitsWindow" 5. 6. 10}" |
({3. 2. 7} collect: #+ `er <- 3) sort. "--> {"SortedArray traitsWindow" 5. 6. 10}" |
||
ExtensibleArray new `>> [addLast: 3. addFirst: 4. ]. "--> {"ExtensibleArray traitsWindow" 4. 3}"</ |
ExtensibleArray new `>> [addLast: 3. addFirst: 4. ]. "--> {"ExtensibleArray traitsWindow" 4. 3}"</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Line 4,075: | Line 4,075: | ||
* '''Dictionary''': objects are ''indexed'' by an arbitrary key, e.g. a string |
* '''Dictionary''': objects are ''indexed'' by an arbitrary key, e.g. a string |
||
< |
<syntaxhighlight lang="smalltalk">|anOrdered aBag aSet aSorted aSorted2 aDictionary| |
||
anOrdered := OrderedCollection new. |
anOrdered := OrderedCollection new. |
||
Line 4,106: | Line 4,106: | ||
at: 'Set' put: aSet; |
at: 'Set' put: aSet; |
||
at: 'SortedCollection' put: { aSorted. aSorted2 }. |
at: 'SortedCollection' put: { aSorted. aSorted2 }. |
||
aDictionary printNl.</ |
aDictionary printNl.</syntaxhighlight> |
||
Output: |
Output: |
||
Line 4,125: | Line 4,125: | ||
A Tcl list is called an array in other languages (an integer-indexed list of values). |
A Tcl list is called an array in other languages (an integer-indexed list of values). |
||
< |
<syntaxhighlight lang="tcl">set c [list] ;# create an empty list |
||
# fill it |
# fill it |
||
lappend c 10 11 13 |
lappend c 10 11 13 |
||
Line 4,136: | Line 4,136: | ||
puts [llength $l] |
puts [llength $l] |
||
} |
} |
||
show_size $c</ |
show_size $c</syntaxhighlight> |
||
A Tcl array is an associative array (aka hash). Arrays are collections of ''variables'' indexable by name, and not collections of values. An array cannot be passed to a procedure be value: it must either be passed by name or by its serialized representation. Tcl arrays also are strictly one-dimensional: arrays cannot be nested. However, multi-dimensional arrays can be simulated with cleverly constructed key strings. |
A Tcl array is an associative array (aka hash). Arrays are collections of ''variables'' indexable by name, and not collections of values. An array cannot be passed to a procedure be value: it must either be passed by name or by its serialized representation. Tcl arrays also are strictly one-dimensional: arrays cannot be nested. However, multi-dimensional arrays can be simulated with cleverly constructed key strings. |
||
< |
<syntaxhighlight lang="tcl"># create an empty array |
||
array set h {} |
array set h {} |
||
# add some pair |
# add some pair |
||
Line 4,163: | Line 4,163: | ||
puts "array has [llength [array names arr]] keys" |
puts "array has [llength [array names arr]] keys" |
||
} |
} |
||
numkeys_bycopy [array get h]</ |
numkeys_bycopy [array get h]</syntaxhighlight> |
||
{{works with|Tcl|8.5}} |
{{works with|Tcl|8.5}} |
||
Line 4,169: | Line 4,169: | ||
A Tcl dictionary is an associative array ''value'' that contains other values. Hence dictionaries can be nested and arbitrarily deep data structures can be created. |
A Tcl dictionary is an associative array ''value'' that contains other values. Hence dictionaries can be nested and arbitrarily deep data structures can be created. |
||
< |
<syntaxhighlight lang="tcl"># create an empty dictionary |
||
set d [dict create] |
set d [dict create] |
||
dict set d one 1 |
dict set d one 1 |
||
Line 4,177: | Line 4,177: | ||
set f [dict merge $d $e] |
set f [dict merge $d $e] |
||
dict set f nested [dict create five 5 more [list 6 7 8]] |
dict set f nested [dict create five 5 more [list 6 7 8]] |
||
puts [dict get $f nested more] ;# ==> 6 7 8</ |
puts [dict get $f nested more] ;# ==> 6 7 8</syntaxhighlight> |
||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT |
$$ MODE TUSCRIPT |
||
Line 4,194: | Line 4,194: | ||
collection=APPEND(collection,morestuff) |
collection=APPEND(collection,morestuff) |
||
TRACE *collection |
TRACE *collection |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 4,210: | Line 4,210: | ||
{{works with|bash}} |
{{works with|bash}} |
||
{{works with|ksh}} |
{{works with|ksh}} |
||
< |
<syntaxhighlight lang="bash">a_index=(one two three) # create an array with a few elements |
||
a_index+=(four five) # append some elements |
a_index+=(four five) # append some elements |
||
a_index[9]=ten # add a specific index |
a_index[9]=ten # add a specific index |
||
Line 4,218: | Line 4,218: | ||
for idx in "${!a_index[@]}"; do # interate over the array indices |
for idx in "${!a_index[@]}"; do # interate over the array indices |
||
printf "%d\t%s\n" $idx "${a_index[idx]}" |
printf "%d\t%s\n" $idx "${a_index[idx]}" |
||
done</ |
done</syntaxhighlight> |
||
===Associative arrays=== |
===Associative arrays=== |
||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<syntaxhighlight lang="bash">declare -A a_assoc=([one]=1 [two]=2 [three]=3) # create an array with a few elements |
||
a_assoc+=([four]=4 [five]=5) # add some elements |
a_assoc+=([four]=4 [five]=5) # add some elements |
||
a_assoc[ten]=10 |
a_assoc[ten]=10 |
||
Line 4,229: | Line 4,229: | ||
for key in "${!a_assoc[@]}"; do # interate over the array indices |
for key in "${!a_assoc[@]}"; do # interate over the array indices |
||
printf "%s\t%s\n" "$key" "${a_assoc[$key]}" |
printf "%s\t%s\n" "$key" "${a_assoc[$key]}" |
||
done</ |
done</syntaxhighlight> |
||
{{works with|ksh}} |
{{works with|ksh}} |
||
Change < |
Change <syntaxhighlight lang="bash">declare -A</syntaxhighlight> to <syntaxhighlight lang="bash">typeset -A</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Line 4,247: | Line 4,247: | ||
Lists are written as comma-separated sequences enclosed in |
Lists are written as comma-separated sequences enclosed in |
||
angle brackets, or with the head and tail separated by a colon. |
angle brackets, or with the head and tail separated by a colon. |
||
< |
<syntaxhighlight lang="ursala">x = <1,5,6> |
||
y = <'foo','bar'> |
y = <'foo','bar'> |
||
z = 3:<6,8></ |
z = 3:<6,8></syntaxhighlight> |
||
This function takes a pair of a new head and an existing list, |
This function takes a pair of a new head and an existing list, |
||
and returns one that has the new head "added" to it. |
and returns one that has the new head "added" to it. |
||
< |
<syntaxhighlight lang="ursala">foo ("newhead","existing-list") = "newhead":"existing-list"</syntaxhighlight> |
||
===Sets=== |
===Sets=== |
||
Line 4,258: | Line 4,258: | ||
The order and multiplicities of elements are ignored, so that the followng |
The order and multiplicities of elements are ignored, so that the followng |
||
declarations are equivalent. |
declarations are equivalent. |
||
< |
<syntaxhighlight lang="ursala">x = {'a','b'} |
||
y = {'b','a'} |
y = {'b','a'} |
||
z = {'a','b','a'}</ |
z = {'a','b','a'}</syntaxhighlight> |
||
===Modules=== |
===Modules=== |
||
Line 4,266: | Line 4,266: | ||
Modules are lists in a particular form used to represent |
Modules are lists in a particular form used to represent |
||
key:value pairs, with the key being a character string. |
key:value pairs, with the key being a character string. |
||
< |
<syntaxhighlight lang="ursala">m = <'foo': 1,'bar': 2,'baz': 3></syntaxhighlight> |
||
A module or any list of pairs can be reified into a function |
A module or any list of pairs can be reified into a function |
||
(a.k.a., a hash or finite map) and used in any context where a function is usable, |
(a.k.a., a hash or finite map) and used in any context where a function is usable, |
||
Line 4,275: | Line 4,275: | ||
where <math>r</math> is the root and <math>s</math> is a list of subtrees, which can |
where <math>r</math> is the root and <math>s</math> is a list of subtrees, which can |
||
be of any length. |
be of any length. |
||
<syntaxhighlight lang="ursala">x = |
|||
<lang Ursala>x = |
|||
'z'^: < |
'z'^: < |
||
Line 4,283: | Line 4,283: | ||
'a'^: <'E'^: <>,'j'^: <>>, |
'a'^: <'E'^: <>,'j'^: <>>, |
||
'b'^: <'i'^: <>>, |
'b'^: <'i'^: <>>, |
||
'c'^: <>></ |
'c'^: <>></syntaxhighlight> |
||
===A-trees=== |
===A-trees=== |
||
Line 4,290: | Line 4,290: | ||
representation wherein data are stored only in the leaves at a |
representation wherein data are stored only in the leaves at a |
||
constant depth. |
constant depth. |
||
<syntaxhighlight lang="ursala">x = |
|||
<lang Ursala>x = |
|||
[ |
[ |
||
Line 4,297: | Line 4,297: | ||
4:2: 'baz', |
4:2: 'baz', |
||
4:3: 'volta', |
4:3: 'volta', |
||
4:4: 'pramim']</ |
4:4: 'pramim']</syntaxhighlight> |
||
===Grids=== |
===Grids=== |
||
Line 4,310: | Line 4,310: | ||
of its descendents in the next level. |
of its descendents in the next level. |
||
<syntaxhighlight lang="ursala">g = |
|||
<lang Ursala>g = |
|||
< |
< |
||
Line 4,332: | Line 4,332: | ||
4:12: -3.460494e+00^: <>, |
4:12: -3.460494e+00^: <>, |
||
4:9: 2.840319e+00^: <>, |
4:9: 2.840319e+00^: <>, |
||
4:7: -2.181140e+00^: <>]></ |
4:7: -2.181140e+00^: <>]></syntaxhighlight> |
||
=={{header|V}}== |
=={{header|V}}== |
||
A quote is used for the same purpose in V |
A quote is used for the same purpose in V |
||
< |
<syntaxhighlight lang="v">[4 3 2 1] 5 swap cons |
||
=[5 4 3 2 1]</ |
=[5 4 3 2 1]</syntaxhighlight> |
||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
VBA has a built in collection type |
VBA has a built in collection type |
||
< |
<syntaxhighlight lang="vb">Dim coll As New Collection |
||
coll.Add "apple" |
coll.Add "apple" |
||
coll.Add "banana"</ |
coll.Add "banana"</syntaxhighlight> |
||
=={{header|Vim Script}}== |
=={{header|Vim Script}}== |
||
Line 4,352: | Line 4,352: | ||
=={{header|Visual Basic .NET}}== |
=={{header|Visual Basic .NET}}== |
||
< |
<syntaxhighlight lang="vbnet">Dim toys As New List(Of String) |
||
toys.Add("Car") |
toys.Add("Car") |
||
toys.Add("Boat") |
toys.Add("Boat") |
||
toys.Add("Train")</ |
toys.Add("Train")</syntaxhighlight> |
||
=={{header|Visual FoxPro}}== |
=={{header|Visual FoxPro}}== |
||
Visual FoxPro has a built in Collection class. |
Visual FoxPro has a built in Collection class. |
||
< |
<syntaxhighlight lang="vfp"> |
||
LOCAL loColl As Collection, o, a1, a2, a3 |
LOCAL loColl As Collection, o, a1, a2, a3 |
||
a1 = CREATEOBJECT("animal", "dog", 4) |
a1 = CREATEOBJECT("animal", "dog", 4) |
||
Line 4,383: | Line 4,383: | ||
ENDDEFINE |
ENDDEFINE |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Wren has only Map(hash) and List(array). |
Wren has only Map(hash) and List(array). |
||
< |
<syntaxhighlight lang="ecmascript">var list = [] // Empty Array |
||
list = [1, 2, 3, 4] |
list = [1, 2, 3, 4] |
||
list.add(5) |
list.add(5) |
||
Line 4,402: | Line 4,402: | ||
for (e in map.keys) { |
for (e in map.keys) { |
||
// Do stuff |
// Do stuff |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Z80 Assembly}}== |
=={{header|Z80 Assembly}}== |
||
Line 4,410: | Line 4,410: | ||
A list is just a consecutive section of memory. Lists are mutable if they are in RAM, and are immutable if they are in ROM. Whether they are located in RAM or in ROM depends mostly on the hardware that uses the Z80 CPU. (Typically, programs that are run from CD-ROM or floppy disks can create mutable lists using the method below, but ROM cartridges cannot, even if those cartridges have internal RAM.) |
A list is just a consecutive section of memory. Lists are mutable if they are in RAM, and are immutable if they are in ROM. Whether they are located in RAM or in ROM depends mostly on the hardware that uses the Z80 CPU. (Typically, programs that are run from CD-ROM or floppy disks can create mutable lists using the method below, but ROM cartridges cannot, even if those cartridges have internal RAM.) |
||
< |
<syntaxhighlight lang="z80">List: |
||
byte 1,2,3,4,5</ |
byte 1,2,3,4,5</syntaxhighlight> |
||
To append to a list you need to know where it ends, unfortunately the CPU can't know this without some sort of metadata placed at the beginning of a list. In addition, it is important to have enough free space after a list to append to it successfully. Otherwise you'll "clobber" whatever is stored after the list, which could be other data or executable code. (The Z80 has no segfaults or memory protection of any kind; writes to ROM are silently ignored, and executable code in RAM is overwritten like any other mutable data.) |
To append to a list you need to know where it ends, unfortunately the CPU can't know this without some sort of metadata placed at the beginning of a list. In addition, it is important to have enough free space after a list to append to it successfully. Otherwise you'll "clobber" whatever is stored after the list, which could be other data or executable code. (The Z80 has no segfaults or memory protection of any kind; writes to ROM are silently ignored, and executable code in RAM is overwritten like any other mutable data.) |
||
< |
<syntaxhighlight lang="z80">List: |
||
byte 5 ;size byte |
byte 5 ;size byte |
||
byte 1,2,3,4,5 ;the actual list |
byte 1,2,3,4,5 ;the actual list |
||
Line 4,439: | Line 4,439: | ||
pop hl ;go back to beginning of the list. |
pop hl ;go back to beginning of the list. |
||
inc (hl) ;add 1 to the size byte. |
inc (hl) ;add 1 to the size byte. |
||
ret</ |
ret</syntaxhighlight> |
||
Line 4,445: | Line 4,445: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
< |
<syntaxhighlight lang="zkl">Lists: L(1,2,3).append(4); //-->L(1,2,3,4), mutable list |
||
Read only list: ROList(1,2,3).append(4); // creates two lists |
Read only list: ROList(1,2,3).append(4); // creates two lists |
||
Line 4,454: | Line 4,454: | ||
Data(0,Int,"foo\n","bar").readln() //-->"foo\n" |
Data(0,Int,"foo\n","bar").readln() //-->"foo\n" |
||
Data(0,String,"foo ","bar") //-->9 bytes (2 \0s) |
Data(0,String,"foo ","bar") //-->9 bytes (2 \0s) |
||
Data(0,String,"foo ").append("bar").readln() //-->"foo "</ |
Data(0,String,"foo ").append("bar").readln() //-->"foo "</syntaxhighlight> |