A couple of days I wrote about a ‘returning’ function that I’d written to simplify a bit of F# code that I’ve been working on.
It’s defined like so:
let returning t f = f(t); t
And can then be used like this:
let build (t:Type) = returning (Activator.CreateInstance(t)) (fun t -> t.GetType().GetProperties() |> Array.iter (fun p -> p.SetValue(t, createValueFor p, null)))
While I quite like this function it didn’t quite feel like idiomatic F# to me.
With that idea in mind I decided to try switching the arguments to ‘returning’ around and renaming it so that the code would read more naturally:
let andApply f t = f(t); t
let build (t:Type) = Activator.CreateInstance(t) |> andApply (fun t -> t.GetType().GetProperties() |> Array.iter (fun p -> p.SetValue(t, createValueFor p, null)))
We partially apply the ‘andApply’ function to create a new function which takes in a type which is provided on the left hand side of the ‘|>’ operator.
I think this now reads better than the original version.
What I find interesting is that when writing functions which I intend to be used like this the way I name them is different and the name only makes sense if it’s used in that context.
Using the ‘andApply’ function on its own without making use of partial function application wouldn’t read as cleanly as it does at the moment.