OCaml has arrays, which are very similar to arrays in any other language.
We can create an array by writing something that looks almost like a list!
[| 1 |];;
[| 1; 2; 3 |];;
- : int array = [|1|]
- : int array = [|1; 2; 3|]
To access a value at an array, we use dot notation. Arrays are zero-indexed.
let a = [|1; 2; 3|];;
a.(0);;
val a : int array = [|1; 2; 3|]
- : int = 1
If you try to index past the end of an array, you get an Invalid_argument exception:
a.(42);;
Exception: Invalid_argument "index out of bounds".
Raised by primitive operation at unknown location
Called from Toploop.load_lambda in file "toplevel/toploop.ml", line 212, characters 17-27
To mutate a value at an array, you can use the left arrow (<-) syntax.
a.(0);;
a.(0) <- 42;;
a.(0);;
- : int = 1
- : unit = ()
- : int = 42
What if we wanted to implement vectors) with arrays?
type vec = float array;;
type vec = float array
What if we wanted to print out each value in the array? We can loop over them!
let vec_print v =
for i = 0 to Array.length v - 1 do
print_float v.(i); print_newline ()
done;;
let v = [|1.; 0.|];;
vec_print v;;
val vec_print : float array -> unit = <fun>
val v : float array = [|1.; 0.|]
1. 0.
- : unit = ()
Note that we use Array.length to get the length of the array, and we deduct one beacsue they are off by one errors.
But there are more better, functional ways to do this. The array standard library provides Array.iter (hey, it's JavaScript's Array.prototype.map)
let vec_print =
let print_elt n =
print_float n; print_newline ()
in Array.iter print_elt;;
vec_print v;;
val vec_print : float array -> unit = <fun>
1. 0.
- : unit = ()
They Printf.printf function can make this even easier!
(For some reason, jupyter doesn't like Printf.printf, but trust me, this works)
let vec_print = Array.iter (Printf.printf "%F\n");;
vec_print v;;
val vec_print : float array -> unit = <fun>
- : unit = ()