I have recently started writing my library of business applications written in C# into F# in order to determine if the language can handle the sort of business applications that I write that use a third-party Windows .NET Framework library. So far everything I have tried has worked, although some things with using C# class libraries are strange, but what I struggle with is that my code looks very imperative in style and try as I might, I can’t always find a way to break out of it.
Here is an example, in pseudo-code.
var session = new Session
session.Start server user password
var loan = session.Loans.Open loanGuid false false
var dec1 = if loan.Fields[“field1”].IsEmpty then 0.00M else (cast to decimal) loan.Fields[“field1”].Value
var dec2 = if loan.Fields[“field2”].IsEmpty then 0.00M else (cast to decimal) loan.Fields[“field2”].Value
// Print out the field values
loan.Close
session.End
Pretty simple stuff. But how does that translate to a functional style, trying to follow the principles in “Grokking Functional Programming” of a trying to make as many functions “pure”, with a function:
- Returns only a single value
- Calculates the return value based only on its argument
- Doesn’t mutate any existing values
There are three basic steps to the program: 1) open a session to the server; 2) open a loan given the loan’s GUID; and extract the data from the fields of the loan.
Step 1 requires you pass the server, user, and password data then return the session object. So isolating that into a function seems pretty straightforward, unless I have more than one function that needs that session.
Step 2 requires the session object, so I can see passing that in, but it is the caller of those two functions that start to look like imperative coding.
Step 3 requires the loan object, so again I can see passing that in as an argument, but again the caller now looks like imperative (step-by-step) code.
I can see how the books define how to do it, for simplistic examples that have no side effects, but I am just not getting it for real-world programming.
I haven’t finished the book, to be honest, so I am hoping it becomes clearer, but I was hoping for a pointer to some example F# code that might illustrate how a traditional program like the above would be written in a functional style.
Right now my style is a bit of a hybrid. I break things down into small, single-purpose functions as much as I can, but generally end up with a big function that consists of step-by-step instructions using all the little functions.