OCaml Array Slice?

3.1k views Asked by At

I'm learning OCaml, and one thing that I have not been able to discover how to do is taking a slice of an array. For example, if I want to extract the subarray of 3 elements starting from index 2, I have to do: [|array.(2); array.(3); array.(4)|]. This gets tedious. Is there any function that can easily and quickly give an array slice? If not, how would I go about rolling my own function for such behaviour?

Really appreciate the help, thanks!

2

There are 2 answers

0
V. Michel On BEST ANSWER

Array.sub is easier to use than blit :

let v=[|0;1;2;3;4;5|];;
let v'=Array.sub v 2 3;;
# val v' : int array = [|2; 3; 4|]

Array.sub a start len returns a fresh array of length len,
containing the elements number start to start + len - 1 of array a.

1
Pierre G. On

There is Array.blit v1 o1 v2 o2 len copies len elements from array v1, starting at element number o1, to array v2, starting at element number o2.

You can also use Array.init int -> (int -> 'a) -> 'a array :

let b = Array.init 3 (fun x -> array.(x+2));;