I do love the fact that F# (and functional programming in general) gives a developer the tools to make it easy to build simple code.
I was hacking together a function to convert a DateTime to a Unix Time Stamp (for using with the Meetup Restful API). This was my initial pass at it:
let unixTimeStamps startDate endDate= let startOfEpoch = new DateTime(1970,1,1) let startTS = uint64 (startDate - startOfEpoch).TotalMilliseconds let endTS = uint64 (endDate - startOfEpoch).TotalMilliseconds (startTS, endTS)
(BTW that may not be the exact working code but it should give the idea.)
Then I thought to myself–why should I return a tuple? If I simplify the function to simply convert a DateTime to a UTS, I can just call it twice. So I got this:
let unixTimeStamp d = let startOfEpoch = new DateTime(1970,1,1) uint64 (d - startOfEpoch).TotalMilliseconds
Simpler but still not as simple as I could make it. I was bothered by the fact that I had to truncate the decimal part of the returned timespan. I had to truncate it because Meetup’s API balks at a time span with a fraction on the end of it. So I modified the function one more time to make it both simpler and more generic:
let unixTimeStamp d = let startOfEpoch = new DateTime(1970,1,1) (d - startOfEpoch).TotalMilliseconds
And I added a little function composition to handle Meetup’s little quirk:
let fixUnixTimeStampForMeetup = unixTimeStamp >> uint64
At any rate, this is part of the reason I’ve got such a crush on FP and F#. It does make it easy to build simple, reusable but still generic code.