Arrays: Difference between revisions

12,198 bytes added ,  23 days ago
m
 
(17 intermediate revisions by 11 users not shown)
Line 730:
<syntaxhighlight lang="ada">procedure Array_Test is
 
A,type BExample_Array_Type :is array (1..20) of Integer;
A, B : Example_Array_Type;
 
-- Ada array indices may begin at any value, not just 0 or 1
C : array (-37..20) of integerInteger;
 
-- Ada arrays may be indexed by enumerated types, which are
Line 756 ⟶ 757:
Centered : Arr (-50..50) := (0 => 1, Others => 0);
 
Result : Integer;
begin
 
A := (others => 0); -- Assign whole array
B := (1 => 1, 2 => 1, 3 => 2, others => 0);
-- Assign whole array, different values
A (1) := -1; -- Assign individual element
Line 766 ⟶ 767:
A (3..5) := (2, 4, -1); -- Assign a constant slice
A (3..5) := A (4..6); -- It is OK to overlap slices when assigned
 
Fingers_Extended(Fingers'First) := False; -- Set first element of array
Fingers_Extended(Fingers'Last) := False; -- Set last element of array
 
end Array_Test;</syntaxhighlight>
Line 2,993 ⟶ 2,994:
=={{header|Ecstasy}}==
Arrays use the [] syntax from C, use zero-based indexing, have a literal syntax, and are implemented by the [https://github.com/xtclang/xvm/blob/master/lib_ecstasy/src/main/x/ecstasy/collections/Array.x Array] class.
<syntaxhighlight lang="java">Int[] literalArray = [1,2,3];
Int[] fixedLengthArray = new Int[10];
Int[] variableArray = new Int[];
 
There are four mutability modes for the Array class, defined by the Array.Mutability enumeration. Here are some examples of how to use these different modes, and to create and manipulate arrays:
assert literalArray.size == 3; // array size
Int n = literalArray[2]; // array access
fixedLengthArray[4] = 12345; // replace value at index
 
<syntaxhighlight lang="java">
fixedLengthArray += 6789; // "add" a value (creates an array copy)
module test {
variableArray += 6789; // "add" a value (efficient append)</syntaxhighlight>
void show(Object o=Null) {
@Inject Console console;
console.print(o);
}
 
void run() {
// an array literal has Constant mutability; it is **not** mutable
immutable Int[] literalArray = [1,2,3];
show($"{literalArray=}, {&literalArray.actualType=}");
 
// obtaining the size or any element of an array is easy
show($"{literalArray.size=}, {literalArray[2]=}");
 
// modifications to a Constant array result in a new Constant array;
// in Computer Science, this is called a persistent data structure
immutable Int[] biggerArray = literalArray + 4;
show($"{biggerArray=}, {&biggerArray.actualType=}");
 
immutable Int[] biggestArray = biggerArray + biggerArray;
show($"{biggestArray=}, {&biggestArray.actualType=}");
 
// arrays can be accessed using the bracket operators
show($"element at {biggestArray[2]=}");
 
// attempts to modify an immutable array "in place" will result in an
// exception at runtime
try {
biggestArray[2] = 99;
} catch (ReadOnly e) {
show($"immutable array not modified: {biggestArray=}");
}
 
// fixed-size arrays are like C/Java/C# arrays; their elements are
// all set to the default value of the array Element type
Int[] fixedLengthArray = new Int[10];
show($"element at {fixedLengthArray[2]=}");
 
// you can also initialize all the elements to a specific value
Int[] negOnes = new Int[3](-1);
show($"{negOnes=}");
 
// ... or using a lambda
Int[] counting = new Int[5](i -> i);
show($"{counting=}");
 
// attempts to modify a fixed-size array "in place" will succeed
counting[1] = 99;
show($"replaced [1]=99: {counting=}");
 
// attempts to add or delete elements from a fixed-size array will
// raise an exception
try {
counting += 101;
} catch (ReadOnly e) {
show($"Fixed mutability array not appendable: {counting=}");
}
 
// you can ask an array for its mutability
show($"{literalArray.mutability=}, {fixedLengthArray.mutability=}");
 
// you can convert an array from one mutability to another; the
// Persistent mutability is just like the Constant mutability,
// except that the array doesn't have to be immutable, so the
// array can hold elements that are mutable, but no elements can
// be added, removed, or replaced
Int[] constantToMutable = biggestArray.toArray(Mutable);
show($|{constantToMutable=}, {&constantToMutable.actualType=},\
| {constantToMutable.mutability=}
);
Int[] constantToFixed = biggestArray.toArray(Fixed);
show($|{constantToFixed=}, {&constantToFixed.actualType=},\
| {constantToFixed.mutability=}
);
Int[] fixedToPersistent = counting.toArray(Persistent);
show($|{fixedToPersistent=}, {&fixedToPersistent.actualType=},\
| {fixedToPersistent.mutability=}
);
Int[] fixedToConstant = counting.toArray(Constant);
show($|{fixedToConstant=}, {&fixedToConstant.actualType=},\
| {fixedToConstant.mutability=}
);
 
// a slice of an array is an array; this is very handy
Int[] slice = constantToMutable[1..2];
show($"{slice=}");
 
// slices may rely on the array that they are sliced from; to ensure that
// changes to the original array don't appear in the slice, the slice
// must be reified
constantToMutable[1] = 17; // this will appear in the slice
slice = slice.reify();
constantToMutable[2] = 18; // this will NOT appear in the slice
show($"{constantToMutable=}, {slice=}");
 
// slices can be inclusive or exclusive
show($"{constantToMutable[1..2]=}");
show($"{constantToMutable[1..<2]=}");
show($"{constantToMutable[1>..2]=}");
show($"{constantToMutable[1>..<2]=}");
 
// creating a new Mutable array uses the simplest form of the constructor;
// a Mutable array
Int[] variableArray = new Int[];
show($"new {variableArray=}");
 
// you can specify an estimated capacity for a new Mutable array, but the
// capacity is just an optimization hint!
Int[] willBeGiantArray = new Int[](999);
show($"new {willBeGiantArray=}, {willBeGiantArray.capacity=}");
 
// you can easily add and remove data from a Mutable array
for (Int i : 10..1) {
variableArray.add(i);
}
show($"NASA count-down: {variableArray=}");
 
// remove unlucky numbers in Japanese
variableArray.remove(4);
show($"lucky count-down: {variableArray=}");
 
// delete by index works as well
variableArray.delete(variableArray.size-1);
show($"aborted count-down: {variableArray=}");
}
}
</syntaxhighlight>
 
{{out}}
<pre>
literalArray=[1, 2, 3], &literalArray.actualType=immutable Array<Int>
literalArray.size=3, literalArray[2]=3
biggerArray=[1, 2, 3, 4], &biggerArray.actualType=immutable Array<Int>
biggestArray=[1, 2, 3, 4, 1, 2, 3, 4], &biggestArray.actualType=immutable Array<Int>
element at biggestArray[2]=3
immutable array not modified: biggestArray=[1, 2, 3, 4, 1, 2, 3, 4]
element at fixedLengthArray[2]=0
negOnes=[-1, -1, -1]
counting=[0, 1, 2, 3, 4]
replaced [1]=99: counting=[0, 99, 2, 3, 4]
Fixed mutability array not appendable: counting=[0, 99, 2, 3, 4]
literalArray.mutability=Constant, fixedLengthArray.mutability=Fixed
constantToMutable=[1, 2, 3, 4, 1, 2, 3, 4], &constantToMutable.actualType=Array<Int>, constantToMutable.mutability=Mutable
constantToFixed=[1, 2, 3, 4, 1, 2, 3, 4], &constantToFixed.actualType=Array<Int>, constantToFixed.mutability=Fixed
fixedToPersistent=[0, 99, 2, 3, 4], &fixedToPersistent.actualType=Array<Int>, fixedToPersistent.mutability=Persistent
fixedToConstant=[0, 99, 2, 3, 4], &fixedToConstant.actualType=immutable Array<Int>, fixedToConstant.mutability=Constant
slice=[2, 3]
constantToMutable=[1, 17, 18, 4, 1, 2, 3, 4], slice=[17, 3]
constantToMutable[1..2]=[17, 18]
constantToMutable[1..<2]=[17]
constantToMutable[1>..2]=[18]
constantToMutable[1>..<2]=[]
new variableArray=[]
new willBeGiantArray=[], willBeGiantArray.capacity=0
NASA count-down: variableArray=[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
lucky count-down: variableArray=[10, 9, 8, 7, 6, 5, 3, 2, 1]
aborted count-down: variableArray=[10, 9, 8, 7, 6, 5, 3, 2]
</pre>
 
=={{header|EGL}}==
Line 3,070 ⟶ 3,223:
 
=={{header|Elena}}==
ELENA 56.0x:
 
Static array
<syntaxhighlight lang="elena"> var staticArray := new int[]{1, 2, 3};</syntaxhighlight>
Generic array
<syntaxhighlight lang="elena"> var array := system'Array.allocate:(3);
array[0] := 1;
array[1] := 2;
Line 3,086 ⟶ 3,239:
Dynamic array
<syntaxhighlight lang="elena"> var dynamicArray := new system'collections'ArrayList();
dynamicArray.append:(1);
dynamicArray.append:(2);
dynamicArray.append:(4);
 
dynamicArray[2] := 3;</syntaxhighlight>
Line 3,719 ⟶ 3,872:
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">window 1, @"FutureBasic Arrays"
window 1, @"FutureBasic Arrays", (0,0,480,450)
 
begin globals
Line 3,779 ⟶ 3,933:
gA1(10) = 67
for i = 0 to fn DynamicNextElement( dynamic(gA1) ) - 1
print gA1(i),
next
print
 
gA1(5) = 19
gA1(10) = 22
for i = 0 to fn DynamicNextElement( dynamic(gA1) ) - 1
print gA1(i),
next
print
 
gA2(0) = "Kilo"
gA2(1) = "Lima"
gA2(5) = "Mike"
for i = 0 to fn DynamicNextElement( dynamic(gA2) ) - 1
print gA2(i),
next
print
 
gA2(1) = "November"
gA2(6) = "Oscar"
for i = 0 to fn DynamicNextElement( dynamic(gA2) ) - 1
print gA2(i),
next
print : print
end fn
 
Line 3,883 ⟶ 4,037:
for i = 0 to len(a1) - 1
print a1[i],
next
print : print
end fn
 
void local fn FB_MDA
long i
text ,, fn ColorGray
print @"// FB MDA - mutable, dynamic, multi-dimensional"
text
mda_add = @"Alpha"
mda_add = @"Romeo"
mda_add = @"Mike"
for i = 0 to mda_count - 1
print mda(i),
next
print
mda_swap(0),(2)
mda(1) = @"Delta"
for i = 0 to mda_count - 1
print mda(i),
next
end fn
Line 3,891 ⟶ 4,072:
fn CoreFoundationMutableFixedLength
fn CoreFoundationMutableDynamic
fn FB_MDA
 
HandleEvents</syntaxhighlight>
</syntaxhighlight>
 
{{out}}
Line 3,921 ⟶ 4,104:
Juliet Golf India
Foxtrot Golf Hotel
 
// FB MDA - mutable, dynamic, multi-dimensional
Alpha Romeo Mike
Mike Delta Alpha
</pre>
 
Line 4,524 ⟶ 4,711:
print(d[1])
}</syntaxhighlight>
 
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">> (var my-list [1 2 3 4 5]) ;syntactic sugar
[1 2 3 4 5]
 
> (var my-list (vec 1 2 3 4 5))
[1 2 3 4 5]
 
> my-list
[1 2 3 4 5]
 
> (3 my-list) ;fourth element
4
 
> (-1 my-list) ;last element
5
 
> (append my-list 100)
[1 2 3 4 5 100]
 
> my-list ;variables are immutable so my-list cannot be changed without being redefined
[1 2 3 4 5]</syntaxhighlight>
 
=={{header|Io}}==
Line 5,061 ⟶ 5,270:
println: foo popFront. ;; "front"
println: foo. ;; [1, 99]</syntaxhighlight>
 
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
myArray is list of numbers
 
procedure:
# add elements
push 1 to myArray
push 2 to myArray
push 3 to myArray
 
# access elements
display myArray:0 lf
 
# store elements
store 99 in myArray:0
 
# remove elements
remove element at 1 from myArray
delete last element of myArray
 
# clear array
clear myArray
</syntaxhighlight>
 
=={{header|LFE}}==
Line 5,885 ⟶ 6,118:
FunctionEnd
</syntaxhighlight>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
let x = [1 2 3]
 
print $x
 
# Both are equivalent
print $x.1 ($x | get 1)
 
# Shadowing the original x
let x = $x | append 4
print $x
 
# Using mut
mut y = [a b c]
print $y
$y = $y | append d
print $y
</syntaxhighlight>
{{out}}
<pre>
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
╰───┴───╯
 
2
2
╭───┬───╮
│ 0 │ 1 │
│ 1 │ 2 │
│ 2 │ 3 │
│ 3 │ 4 │
╰───┴───╯
 
╭───┬───╮
│ 0 │ a │
│ 1 │ b │
│ 2 │ c │
╰───┴───╯
 
╭───┬───╮
│ 0 │ a │
│ 1 │ b │
│ 2 │ c │
╰───┴───╯
</pre>
 
=={{header|Oberon-2}}==
Line 7,586 ⟶ 7,868:
/end-free
</syntaxhighlight>
 
{{works with|ILE RPG v7.1+}}
<nowiki>**</nowiki>free
//-Static array
//--def of 10 el array of integers, initialised to zeros
dcl-s array int(10) dim(10) inz;
//--def an el
dcl-s el_1 int(10) inz(0);
//-assign first el
//--first element of RPG array is indexed with 1
array(1) = 111;
//-get first el of array
el_1 = array(1);
//--display it
dsply ('First el of array='+%char(el_1));
//--displays: First el of array=111
//---or shorter, without "el_1"
dsply ('First el of array='+%char(array(1)));
//--displays: First el of array=111
 
=={{header|RPL}}==
Arrays have a predefined size and can only contain floating point numbers.
They can be created either by enumerating their elements one by one or by creating an array with the same value everywhere:
[ 1 2 3 4 5 ]
{ 5 } -1 CON <span style="color:grey">@ create the array [ -1 -1 -1 -1 -1 ]</span>
To assign a value, you can use either <code>PUT</code> or <code>PUTI</code>. <code>PUT</code> returns only the updated array - other input arguments are gone - whilst <code>PUTI</code> leaves in stack the index, incremented by one : you can then easily assign another value to the following position.
[ 1 2 3 4 5 ] 3 10 PUT
returns:
1: [ 1 2 10 4 5 ]
but
[ 1 2 3 4 5 ] 3 10 PUTI
returns:
2: [ 1 2 10 4 5 ]
1: 4
Similarly, you can use <code>GET</code> or <code>GETI</code> to retrieve an element.
[ 10 20 30 40 50 ] 3 GET
returns:
1: 30
but
[ 10 20 30 40 50 ] 3 GETI
returns:
3: [ 10 20 30 40 50 ]
2: 4
1: 30
Another useful data structure in RPL is the list, which is very similar in use to arrays: <code>PUT</code>, <code>PUTI</code>, <code>GET</code> and <code>GETI</code> give the same results. Lists can contain any kind of objects, including lists. Beside direct assignment through <code>PUT</code>, it is also possible to append an element at the beginning or the end of the list with the <code>+</code> operator.
In recent RPL versions, several functions such as <code>SORT</code> can be applied only to lists, which make this data structure very versatile. The only drawback is the necessity to create a list element by element
by direct enumeration:
{ 1 2 3 4 5 }
by concatenation:
{ 1 2 3 } { 4 5 } +
or through a loop:
{ } 1 5 '''FOR''' j j + '''NEXT'''
 
=={{header|Ruby}}==
Line 8,136 ⟶ 8,474:
slate[7]> x at: 0.
1</syntaxhighlight>
 
=={{header|SmallBASIC}}==
<syntaxhighlight lang="SmallBASIC">
' One dimensional arrays
DIM A ' empty array
DIM B(3) ' empty array with 4 elements
DIM C(2 TO 4) ' empty array with elements 2,3 and 4
D = [1,2,3,4] ' assign array in one statement
E = ["one", "two", "three"] ' string array
F = [1, "two", [1,2,3]] ' arrays can contain mixed data types
 
B[0] = 1 ' use [] or () to assign value to
B(1) = 2 ' element or access elements
 
A << 2 ' append element to an array
 
print F ' print whole array -> Output: [1,two,[1,2,3]]
print F[0] ' print first element -> Output: 1
print F(1) ' print second element -> Output: two
 
' Multi dimensional arrays
DIM A(2,0) ' column array (vector) with 3 elements
DIM B(2,2) ' empty 2D array (matrix) with 3x3 elements
DIM C(2,2,2) ' empty 3D array with 3x3x3 elements
 
A[0,0] = 1
A[1,0] = 2
A[2,0] = 3
 
' Math with arrays
 
A = [1,2,3]
B = [4,5,6]
 
print A + B ' Output: [5,7,9]
print 3 * A ' Output: [3,6,9]
print A * B ' Output: [4,10,18]
 
C = [1;2;3] ' vector
D = [1,2,3;4,5,6;7,8,9] ' 2D matrix
 
print D * C ' matrix * vector -> Output [14;32;50]
print D * D ' matrix * matrix -> Output [30,36,42;66,81,96;102,126,150]
</syntaxhighlight>
 
 
=={{header|Smalltalk}}==
Line 8,359 ⟶ 8,742:
// Natural indexes start at 1
$a(1) -> !OUT::write
'
' -> !OUT::write
 
// But you can have an array start at any index
def b: -5:['foo', 'bar', 'qux'];
$b(-3) -> !OUT::write
'
' -> !OUT::write
Line 8,380 ⟶ 8,769:
[1, 2, 3, 5, 7, 11]
1
qux
[3, 5, 7, 11]
[5, 1, 7]
Line 8,992 ⟶ 9,382:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">var arr = []
arr.add(1)
arr.add(2)
2

edits