F#: The Kestrel Revisited
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 idiomatic F# we would tend to design our functions in such a way that we can pipe data through a series of them by making use of the forward or function composition operators.
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.
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.