Collections

From Rosetta Code
Revision as of 08:54, 16 February 2009 by 79.213.124.105 (talk)
Task
Collections
You are encouraged to solve this task according to the task description, using any language you may know.
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.

Collections are abstractions to represent sets of values. In strongly-typed languages, the values are typically of a common data type.

Create a collection, and add a few values to it.

C++

This example may be incorrect due to a recent change in the task requirements or a lack of testing. Please verify it and remove this message. If the example does not match the requirements or does not work, replace this message with Template:incorrect or fix the code yourself.

[[Category:{{{1}}} examples needing attention]]Property "Example requires attention" (as page type) with input value "{{{1}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process.

C++ has a range of different collections optimized for different use cases. Note that in C++, objects of user-defined types are mostly treated just like objects of built-in types; especially there's no different treatment for collections. Thus all collections can simply be demonstrated with the built-in type int. For user-defined types, just replace int with the user-defined type. Any type which goes into a collection must be copyable and assignable (which in general is automatically the case unless you explicitly disallow it).

Note however that C++ collections store copies of the objects given to them, so you'll lose any polymorphic behaviour. If you need polymorphism, use a collection of pointers (or smart pointers like boost::shared_ptr).

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.

<lang cpp>#include <vector>

std::vector<int> v; // empty vector v.push_back(5); // insert a 5 at the end v.insert(v.begin(), 7); // insert a 7 at the beginning</lang>

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.

<lang cpp>#include <deque>

std::deque<int> d; // empty deque d.push_back(5); // insert a 5 at the end d.push_front(7); // insert a 7 at the beginning d.insert(v.begin()+1, 6); // insert a 6 in the middle</lang>

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.

<lang cpp>#include <list>

std::list<int> l; // empty list l.push_back(5); // insert a 5 at the end l.push_front(7); // insert a 7 at the beginning std::list::iterator i = l.begin(); ++l; l.insert(i, 6); // insert a 6 in the middle</lang>

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 a and b is smaller using a<b (there's also a way to define sets with an user-defined order, in which case this restriction doesn't apply).

<lang cpp>#include <set>

std::set<int> s; // empty set s.insert(5); // insert a 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)</lang>

multiset

A multiset is like a set, except the same element may occur multiple times.

<lang cpp>#include <multiset>

std::multiset<int> m; // empty multiset m.insert(5); // insert a 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)</lang>

D

D has static arrays. <lang d>int[3] array; array[0] = 5; // array.length = 4; // compile-time error </lang>

D has dynamic arrays. <lang d>int[] array; array ~= 5; // append 5 array.length = 3; array[3] = 17; // runtime error: out of bounds. check removed in release mode. array = [2, 17, 3]; writefln(array.sort); // 2, 3, 17 </lang>

D has associative arrays. <lang d>int[int] array; // array ~= 5; // it doesn't work that way! array[5] = 17; array[6] = 20; // prints "[5, 6]" -> "[17, 20]" - although the order is not specified. writefln(array.keys, " -> ", array.values); assert(5 in array); // returns a pointer, by the way if (auto ptr = 6 in array) writefln(*ptr); // 20 </lang>

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.

? def constList := [1,2,3,4,5]
# value: [1, 2, 3, 4, 5]

? constList.with(6)
# value: [1, 2, 3, 4, 5, 6]

? def flexList := constList.diverge()
# value: [1, 2, 3, 4, 5].diverge()

? flexList.push(6)
? flexList
# value: [1, 2, 3, 4, 5, 6].diverge()

? constList
# value: [1, 2, 3, 4, 5]
? def constMap := [1 => 2, 3 => 4]
# value: [1 => 2, 3 => 4]

? constMap[1]
# value: 2
? def constSet := [1, 2, 3, 2].asSet()
# value: [1, 2, 3].asSet()

? constSet.contains(3)
# value: true

J

J is an array-oriented language -- it treats all data as collections and processes collections natively. Its built in (primitive) functions are specifically designed to handle collections.

J is weakly typed, and hetergenous collections are possible via "boxing" (analogous to a "variant" data type).

   c =: 0 10 20 30 40 NB.  A collection

   c, 50              NB.  Append 50 to the collection
0 10 20 30 40 50
   _20 _10 , c        NB.  Prepend _20 _10 to the collection
_20 _10 0 10 20 30 40
  
   ,~  c               NB.  Self-append
0 10 20 30 40 0 10 20 30 40
   ,:~  c              NB.  Duplicate
0 10 20 30 40
0 10 20 30 40
  
   30 e. c             NB.  Is 30 in the collection?
1
   30 i.~c             NB.  Where? 
3
   30 80 e. c          NB.  Don't change anything to test multiple values -- collections are native.
1 0
  
   2 1 4 2 { c         NB.  From the collection, give me items two, one, four, and two again.
20 10 40 20
  
   |.c                 NB.  Reverse the collection
40 30 20 10 0
   1+c                 NB.  Increment the collection
1 11 21 31 41          
   c%10                NB.  Decimate the collection (divide by 10)
0 1 2 3 4
   
   {. c                NB.  Give me the first item
0
   {: c                NB.  And the last
40
   3{.c                NB.  Give me the first 3 items
0 10 20
   3}.c                NB.  Throw away the first 3 items  
30 40
   _3{.c               NB.  Give me the last 3 items 
20 30 40
   _3}.c               NB.  Guess
0 10

     keys_map_  =:  'one';'two';'three'
     vals_map_  =:  'alpha';'beta';'gamma'
   lookup_map_  =:  a:& $: : (dyad def ' (keys i. y) { vals,x')&boxopen
   exists_map_  =:  verb def 'y e. keys'&boxopen

   exists_map_ 'bad key'
0 
   exists_map_ 'two';'bad key'
1 0

   lookup_map_ 'one'
+-----+
|alpha|
+-----+
   lookup_map_ 'three';'one';'two';'one'
+-----+-----+----+-----+
|gamma|alpha|beta|alpha|
+-----+-----+----+-----+
   lookup_map_ 'bad key'
++
||
++
   'some other default' lookup_map_ 'bad key'
+------------------+
|some other default|
+------------------+
   'some other default' lookup_map_ 'two';'bad key'
+----+------------------+
|beta|some other default|
+----+------------------+

   +/ c                NB. Sum of collection
100
   */ c                NB.  Product of collection
0

   i.5                 NB.  Generate the first 5 nonnegative integers
0 1 2 3 4
   10*i.5              NB.  Looks familiar
0 10 20 30 40
   c = 10*i.5          NB.  Test each for equality
1 1 1 1 1
   c -: 10 i.5         NB.  Test for identicality
1

Java

Works with: Java version 1.5+

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.

<lang java>List arrayList = new ArrayList(); arrayList.add(new Integer(0));

//other features of ArrayList //define the type in the arraylist, you can substitute a proprietary class in the "<>" private List<Integer> myarrlist; myarrlist = new ArrayList<Integer>();

//add several values to the arraylist to be summed later int sum; for(int i=0; i<10; i++) {

   myarrlist.add(i);

}</lang>

<lang java>//loop through myarrlist to sum each entry for(i=0; i<myarrlist.size(); i++) {

   sum+=myarrlist.get(i);

}</lang> or <lang java>for(int i:myarrlist){

   sum+= i;

}</lang>

<lang java>//remove the last entry in the ArrayList myarrlist.remove(myarrlist.size()-1)

//clear the ArrayList myarrlist.clear();</lang>

JavaScript

This example may be incorrect due to a recent change in the task requirements or a lack of testing. Please verify it and remove this message. If the example does not match the requirements or does not work, replace this message with Template:incorrect or fix the code yourself.

[[Category:{{{1}}} examples needing attention]]Property "Example requires attention" (as page type) with input value "{{{1}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process.

<lang javascript>var array = []; array.push('abc'); array.push(123); array.push(new MyClass); alert( array[2] );</lang>

<lang javascript>var map = {}; map['foo'] = 'xyz'; //equivalent to: map.foo = 'xyz'; map['bar'] = new MyClass; //equivalent to: map.bar = new MyClass; map['1x; ~~:-b'] = 'text'; //no equivalent alert( map['1x; ~~:-b'] );</lang>

Logo has a list-like protocol (first, butfirst, etc.) which works on three different data types:

  • members of a list: [one two three]
  • items in an array: {one two three}
  • characters in a word: "123

Lua

Lua has only one type of collection, the table.

collection = {0, '1'}
collection = {["foo"] = 0, ["bar"] = '1'} -- a collection of key/value pairs

Objective-C

This example may be incorrect due to a recent change in the task requirements or a lack of testing. Please verify it and remove this message. If the example does not match the requirements or does not work, replace this message with Template:incorrect or fix the code yourself.

[[Category:{{{1}}} examples needing attention]]Property "Example requires attention" (as page type) with input value "{{{1}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process.

Works with: gcc

The NSMutableArray class (defined by OpenStep and derivated as GNUstep or Cocoa) in Objective C provides a simple, editable array data structure.

NSMutableArray *array = [[NSMutableArray alloc] init];

[array addObject:@"String1"];
[array addObject:@"String2"];
[array insertObject:@"String3" atIndex:1];

NSLog( @"%@, %@, %@", [array lastObject], [array objectAtIndex:0], [array objectAtIndex:1] );
// prints: String2, String1, String3

Perl

This example may be incorrect due to a recent change in the task requirements or a lack of testing. Please verify it and remove this message. If the example does not match the requirements or does not work, replace this message with Template:incorrect or fix the code yourself.

[[Category:{{{1}}} examples needing attention]]Property "Example requires attention" (as page type) with input value "{{{1}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process.

Library: IO::FileFile

Collections are just lists. Thus, you can use list functions to manipulate them and store them in arrays.

<lang perl>my @c = (IO::File->new, IO::File->new);

  1. start collection with two objects

push @c, IO::File->new;

  1. add another object to the collection</lang>

PHP

This example may be incorrect due to a recent change in the task requirements or a lack of testing. Please verify it and remove this message. If the example does not match the requirements or does not work, replace this message with Template:incorrect or fix the code yourself.

[[Category:{{{1}}} examples needing attention]]Property "Example requires attention" (as page type) with input value "{{{1}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process.

<lang php>$students = array(); array_push($students, array('name' => 'Joe Smith', 'age' => 21, height=> '72.5', gpa => 3.42 ));</lang>

Python

Works with: Python version 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. <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) collection.append(2) # adding something to the end of the list collection.insert(0, '-1') # inserting a value into the beginning y = collection[0] # now returns a string of "-1" collection.extend([2,'3']) # same as [collection.append(i) for i in [2,'3']] ... but faster collection[2:6] # a "slice" (collection of the list elements from the third up to but not including the sixth) len(collection) # get the length of (number of elements in) the collection collection = (0, 1) # Tuples are immutable (not editable) collection[:] # ... slices work on these too; and this is equivalent to collection[0:len(collection)] collection[-4:-1] # negative slices count from the end of the string collection[::2] # slices can also specify a stride --- this returns all even elements of the collection collection="some string" # strings are treated as sequences of characters x = collection[::-1] # slice with negative step returns reversed sequence (string in this case). collection[::2] == "some string"[::2] # True, literal objects don't need to be bound to name/variable to access slices or object methods collection.__getitem__(slice(0,len(collection),2)) # same as previous expressions. collection = {0: "zero", 1: "one"} # Dictionaries (Hash) collection['zero'] = 2 # Dictionary members accessed using same syntax as list/array indexes. collection = set([0, '1']) # sets (Hash)</lang>

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).

Raven

Numerically indexed List:

[ 1 2 3 'abc' ] as a_list
a_list print
list (4 items)
 0 => 1
 1 => 2
 2 => 3
 3 => "abc"

String key indexed Hash:

{ 'a' 1 'b' 2 } as a_hash
a_hash print
hash (2 items)
 a => 1
 b => 2

Set items:

17 a_list 1 set      # set second item
42 a_hash 'b' set    # set item with key 'b'
42 a_hash:b          # shorthand 

Get items:

a_list 1 get         # get second item
a_hash 'b' get       # get item with key 'b'
a_hash.b             # shorthand

Other stuff:

42 a_list push       # append an item
a_list pop           # remove last item
42 a_list shove      # prepend an item
a_list shift         # remove first item
42 a_list 1 insert   # insert item second, shuffling others down
a_list 1 remove      # retrieve second item, shuffling others up

Ruby

Ruby is a 100% object oriented language, so you can use the default Array or Hash structures as collection objects.

array

<lang ruby># creating an empty array and adding values

a = [] # => [] a[0] = 1 # => [1] a[3] = 2 # => [1, nil, nil, 3]

  1. creating an array with the constructor

a = Array.new # => []</lang>

hash

<lang ruby># creating an empty hash

h = {} # => {} h["a"] = 1 # => {"a" => 1} h["test"] = 2.4 # => {"a" => 1, "test" => 2.4} h[3] = "Hello" # => {"a" => 1, "test" => 2.4, 3 => "Hello"}</lang>

Scala

This example may be incorrect due to a recent change in the task requirements or a lack of testing. Please verify it and remove this message. If the example does not match the requirements or does not work, replace this message with Template:incorrect or fix the code yourself.

[[Category:{{{1}}} examples needing attention]]Property "Example requires attention" (as page type) with input value "{{{1}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process.

val l = List(1,2,3,4,-1,-2,-4)
l.filter{0<} // get the positive values  List(1,2,3,4)
l.head // 1 -- first element
l.tail // List(2,3,4,-1,-2,-4) -- the rest of the list
l.take(3) // List(1,2,3) -- the first 3 elements in the list
l.drop(4) //  List(-1,-2,-4) -- get rid of the first 4 element in the list
88 :: l.tail //  List(88,2,3,4,-1,-2,-4)
l.take(2) ::: 18 :: l.takeRight(2) //  List(1,2,18,-2,-4)

Smalltalk

This example may be incorrect due to a recent change in the task requirements or a lack of testing. Please verify it and remove this message. If the example does not match the requirements or does not work, replace this message with Template:incorrect or fix the code yourself.

[[Category:{{{1}}} examples needing attention]]Property "Example requires attention" (as page type) with input value "{{{1}}}" contains invalid characters or is incomplete and therefore can cause unexpected results during a query or annotation process.

| collection |
collection := #(1 2 3 4 5) asOrderedCollection.
collection add: $a; add: $b.
collection remove: $a.
collection removeAtIndex: 2.

V

A quote is used for the same purpose in V

[4 3 2 1] 5 swap cons
=[5 4 3 2 1]


Visual Basic .NET

       Dim toys As New List(Of String)
       toys.Add("Car")
       toys.Add("Boat")
       toys.Add("Train")