F# Tips

What the heck is the deal with the Microsoft RegEx object? It says it returns a MatchCollection, but it doesn’t look like any collection I’ve ever seen.

As I understand it, the MS regex object goes back — way back. Way back before folks stuck enumerators on things. So it’s a collection. Kinda. I don’t like System Type extensions willy-nilly, but this looked to me like a good place for one. So I do this:

    type System.Text.RegularExpressions.MatchCollection with
        member this.toSeq =
            seq {for i = 0 to this.Count - 1 do yield this.[i]}
        member this.toArray =
            [|for i = 0 to this.Count - 1 do yield this.[i] |]

I have an array and I’d like to write a function that picks a random item from it. How do I do that?

This is another type extension, and it shows the danger of writing type extensions. In this case, the extension assumes that the array is not empty. I could have written around that by returning an option type or something, but then I’d kind of defeat the purpose of writing the extension in the first place.

    type 'a ``[]`` with         
        member x.randomItem = 
            let rnd = new System.Random()
            let idx = rnd.Next(0,x.Length)
    type System.Random with
        /// Generates an infinite sequence of random numbers within the given range.
        member this.GetValues(minValue, maxValue) =
            Seq.initInfinite (fun _ -> this.Next(minValue, maxValue))

I also included how to get an infinite sequence of random numbers.

I hope you’ve enjoyed these tips!

Follow the author on Twitter

July 5, 2018

Leave a Reply

Your email address will not be published. Required fields are marked *