F# Array Slicing

This should be a short post regarding something I hadn’t seen before – F#’s array slicing syntax. One of the problems of coming to F# from another language is that sometimes you just use language features without realising that the new language offers more options – this is one such feature of arrays in F#.

An array slice is really just a way of creating an array made up of a subset of another array. So for example let’s assume we have the following

let array = [| 1; 2; 3; 4; 5; 6 |]

We can access the array via an indexer, but as you probably know, you access the indexer using dot notation, for example

let v = array.[3]

But we can do more than just get a single item, we use the same basic syntax to get slices of the array, for example

// create a new array of items 2 to 4 inclusive
let a = array.[2..4]

// create a new array of items up to and including item 3 (i.e. 0..3)
let b = array.[..3]

// create a new array of items from item 3 until the end of the array
let c = array.[3..]

// create a clone of all elements
let d = array.[*]