Mark Needham

Thoughts on Software Development

F#: The Kestrel Revisited

with 3 comments

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.

Be Sociable, Share!

Written by Mark Needham

May 4th, 2010 at 6:36 pm

Posted in F#

Tagged with

  • Oldrich

    Hi,

    Why don’t you make it this way? It looks more readable to me

    let build (t:Type) =
    let instance = Activator.CreateInstance(t)
    instance.GetType().GetProperties()
    |> Array.iter (fun p -> p.SetValue(instance, createValueFor p, null))
    instance

  • Pingback: Tweets that mention F#: The Kestrel Revisited at Mark Needham -- Topsy.com

  • http://www.markhneedham.com Mark Needham

    @Oldrich – I’ve been playing around with the idea of not storing anything in values where I can avoid – more just to see how the code ends up reading if you do that than anything else.

    Perhaps in this case you’re right and it does read better by assigning a value. I guess it’s all personal opinion!