Thursday, September 6, 2018

Working with Tuples - dereferencing tuples in function declarations

I've been trying to do more little code tidbits to ensure I keep my skills up since I'm rarely coding any more, and F# is a good way to stretch my skills in unfamiliar ways.

I've done a few "useful" things with it now and I'm really enjoying it.  One was purely for fun, another for personal use but not exactly fun, and another for actual work.

One thing I found difficult was working effectively with Tuples, which even though Records are so easy to use in F#, tuples are even easier to use and I have tended to use them perhaps more than I should.
Take this code, which basically just sums the "second value from each tuple in the list"
let list = [(a, 10);(b, 5)]
let aggregateValues = list |> List.sumBy(fun tuple -> snd tuple)
The readability of that is horrible as you start adding more complex types or multi-value tuples.


A really simple tip was shown to me from someone who has actually delivered F# projects
let aggregateValues = list |> List.sumBy(fun (category,value) -> value)
by simply dereferencing the tuple and using appropriate field names, it is much clearer what is happening.  Now I knew this could be done on things like match clauses but I didn't realise you could do this in a method declaration. 


No comments:

Post a Comment