Custom String Sorting

I’m new to F# and I’m working on a simple script to work with some data from an API. One of the values is a ‘rating’ of a company. The available ratings are “AAA”, “AA”, “A”, “BBB”, “BB”, “B”, and “CCC” in that order. I have a collection of companies where each one has a rating. I want to sort the companies by rating. However, if I use a normal sortBy, I’ll get “A” followed by “AA”, followed by “AAA”, etc. which isn’t what I want. Is there a simple way to define a custom sort function to handle collating? Is there some way I can define a ‘Rating’ type and specify the allowed values along with some functions to handle sorting? I’m looking for suggestions that might help me expand my knowledge of how to tackle a problem using F#.



There are really a lot of ways to achieve it.

One of them would be creating a separate enum type Rating as you suggested. So, it will be something like that:

type Rating =
    | A = 0
    | AA = 1
    | AAA = 2
    | B = 3
    | BB = 4
    | BBB = 5
    | CCC = 6

You can read more about enum type in articles that listed below:

Enum types


let sortedData =
    tempData |> Seq.sortBy (fun company -> company.Rating)

Or, if you want to stick to string type you can create custom comparision function and pass it to the Seq.sortWith function.

Or, you can create a map/dictionary (Map<string, int>) that keeps value as an weight for your rating.

Of course, I have mentioned not all of them, but, personally, I would choose a first one.

Thanks. I was actually able to get what I wanted with a simple union type. I just needed to write a simple function to convert my input strings into the type.