Concepts of Programming Languages

(Sean Pound) #1

264 Chapter 6 Data Types


A Perl array can be made to grow by using the push ( puts one or more
new elements on the end of the array) and unshift ( puts one or more new
elements on the beginning of the array), or by assigning a value to the array
specifying a subscript beyond the highest current subscript of the array. An
array can be made to shrink to no elements by assigning it the empty list, ().
The length of an array is defined to be the largest subscript plus one.
Like Perl, JavaScript allows arrays to grow with the push and unshift
methods and shrink by setting them to the empty list. However, negative sub-
scripts are not supported.
JavaScript arrays can be sparse, meaning the subscript values need not be
contiguous. For example, suppose we have an array named list that has 10 ele-
ments with the subscripts 0..9.^5 Consider the following assignment statement:

list[50] = 42;

Now, list has 11 elements and length 51. The elements with subscripts
11..49 are not defined and therefore do not require storage. A reference to a
nonexistent element in a JavaScript array yields undefined.
Arrays in Python, Ruby, and Lua can be made to grow only through meth-
ods to add elements or catenate other arrays. Ruby and Lua support negative
subscripts, but Python does not. In Python, Ruby, and Lua an element or slice
of an array can be deleted. A reference to a nonexistent element in Python
results in a run-time error, whereas a similar reference in Ruby and Lua yields
nil and no error is reported.
Although the ML definition does not include arrays, its widely used imple-
mentation, SML/NJ, does.
The only predefined collection type that is part of F# is the array (other
collection types are provided through the .NET Framework Library). These
arrays are like those of C#. A foreach statement is included in the language
for array processing.

6.5.4 Array Initialization


Some languages provide the means to initialize arrays at the time their storage
is allocated. In Fortran 95+, an array can be initialized by assigning it an array
aggregate in its declaration. An array aggregate for a single-dimensioned array is
a list of literals delimited by parentheses and slashes. For example, we could have

Integer, Dimension (3) :: List = (/0, 5, 5/)

C, C++, Java, and C# also allow initialization of their arrays, but with one
new twist: In the C declaration

int list [] = {4, 5, 7, 83};


  1. The subscript range could just as easily have been 1000.. 1009.

Free download pdf