F# Zen - Array slices

Sorry for not being as regular with blogging, I've been sick and working hard on something pretty exciting. Don will post an announcement sooner or later.

Anyways, did you know that in F# you can easily take out a chunk of an array using an Array Slice? This is a simple syntax for selecting a subset of an array, which creates a new array copying the values. This slice syntax also works for 2D arrays as well in much the same way. (E.g., daysOfYear.[*, ..5])

Here are some simple examples:

 open System
let daysOfWeek = Enum.GetNames( typeof<DayOfWeek> );;

// Standard array slice, elements 2 through 4
daysOfWeek.[2..4];;

// Just specify lower bound, elements 4 to the end
daysOfWeek.[4..];;

// Just specify an upper bound, elements 0 to 2
daysOfWeek.[..2];;

// Specify no bounds, get all elements (clones the array)
daysOfWeek.[*];;

Comments

  • Anonymous
    December 09, 2008
    Nice timing -- I was just trying to find a clean way of doing this on the bus this morning. This was exactly my use case, in fact (skipping the first element in a list of Enum names).

  • Anonymous
    December 09, 2008
    Hehe, that's why they pay me the big bucks :)