Saturday, February 6, 2016

Item and Slice F#

"Slice, I say. Pauca, pauca. Slice! That's my humour."
-- Shakespeare, The Merry Wives of Windsor
Act I, Scene I, Line 125

I've been working my way through Dave Fancher's excellent Book of F# and found an interesting example of indexing and slicing arrays in F#.  Since programming is a full contact sport, here is my take on indexing and slicing in F#.



We have a constructor for a type called Word which takes a string and separates it into words.

type Words(sentence : string)

We implement an index with the Item member.

member x.Item(i) = words.[i]

This allows us to access the words of the string given.

Words(sentence).[1]

We also implement an array slice with the GetSlice member.

member x.GetSlice(s : int option, e : int option)

This allows us to slice the array (substring it) of words in the string given.

Words(sentence).[1..2]

We can go one better than built in slice by allow for range in the slice to be bigger than the number of words.

let longer = 100
Words(sentence).[0..longer]

In order to allow for this we have to check to see if the end is greater than the number of words.

if e > words.Length then words.[s..] else words.[s..e]

and

if e > words.Length then words else words.[..e]

I hope I have shown that F# has some very nice support for objects.