Added draft of section on arrays

This commit is contained in:
Audun Wilhelmsen 2013-12-26 13:43:12 -08:00
parent 2d6b9f7598
commit c7d99743bd
1 changed files with 36 additions and 0 deletions

View File

@ -22,6 +22,42 @@ http://nimrod-lang.org/manual.html
<tr><td>Operator Overloading</td><td>No (Yes w/ C++)</td><td>Yes</td></tr>
<tr><td>Custom Operators</td><td>No</td><td>Yes</td></tr>
</table>
### Arrays
In C an array is more or less syntactic sugar for pointers. In Nimrod, arrays are much more strict and safe to use. They are pass-by-value (meaning they're copied at assignment). When passing an array to a proc in Nimrod, the argument is a read-only reference, meaning it can't be assigned to. Take the following example:
**C:**
```C
void foobar(int z[4]) {
z[5] = 5;
printf("%d\n",z[5]);
}
int main() {
int x[4] = {1, 2, 3, 4};
foobar(x);
printf("%d\n", x[1]);
return 0;
}
```
**Nimrod:**
```Nimrod
proc foobar(z: array[0..3, int]) =
z[5] = 5 # Error: Cannot assign to z
echo z[5] # Error: Index out of bounds.
var x = [1, 2, 3, 4]
foobar(x)
```
The C-code will compile, it may or may not crash. The Nimrod code will not compile. If you mean to change the array that was passed to the procedure, you can change the the signature of the procedure to ```proc foobar(z: var array[0..3, int])```. Now you will only get index out of bounds error. If you change the index in both lines to 1, the code will compile. If the index is a variable, Nimrod will include run-time checks on the bounds of the array.
In C, you can pass an ``int[3]`` to the foobar function, and the compiler will not complain. In this case Nimrod would not compile. You can use an openarray to accept an array of any size, and you can use low(z) and high(z) to query the bounds of the array.
Nimrod arrays can also be indexed from any number. That is, ``z: array[1..4, int]`` is an array of int indexed from 1 to 4. Trying to access ``z[0]`` would throw an index out bounds error.
### Structs - Tuples and Objects
Tuples and Objects in Nimrod are kind of like structs in C, but not really.