Search code examples
arraysocamlslicesub-array

OCaml Array Slice?


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!


Solution

  • 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.