kcrary
August 29, 2023, 4:19pm
1
When calling Array.init, can I rely on the initializer being called in order of increasing index? The documentation page does not seem to commit to that.
Yes, and soon officially yes:
ocaml:trunk
← johnwhitington:trunk
opened 07:43PM - 03 Sep 22 UTC
The function `Array.init` does not promise to call the given function on each el… ement in order, left to right. I think it should. The implementation already conforms, but the documentation does not mention it. `List.init` does specify evaluation order, by contrast.
The motivation is this: imagine we are using a stateful function to read some equal-sized fields of binary data from a source of data (this example is from TrueType fonts):
```
let endCodes = Array.make segCount 0 in
for x = 0 to segCount - 1 do
endCodes.(x) <- read_ushort b
done
```
If we had to do this many times, we could write an ancillary function, of course, But it would be nicer to simply write:
```
let endCodes = Array.init segCount (fun _ -> read_ushort b) in ...
```
We cannot however - according to the current documentation, the values read could come out in any order.
(In fact, searching my existing code, it looks like I've been relying on this undocumented left-to-right order for years... maybe others have too.)