In my code I declared a dictionary to store various counters
let counters = Dictionary<Type, int>()
Later, I need to generate several labels using these counters, like this:
- First type a label is generated for a given type, it should consist of the type name itself:
"MyType" - Subsequent label should be the type name, appended with the number of times a label was previously generated for that type, in parentheses:
"MyType (2)"
Here's how I'm accomplishing this now:
let t : Type = ...
let label =
if (counters.ContainsKey(t)) then
counters.[t] <- counter.[t] + 1
sprintf "%s (%i)" t.Name counters.[t]
else
counters.Add(t, 1)
t.Name
This is exactly how I would write it if I had to use C# (with the exception of the in-line if / else), but after I wrote it F#, it seems clumsy and a little messy. I suspect there is a much more elegant, idiomatic way of writing this in F#. Perhaps using a match expression?