Search code examples
f#pointfree

Creating a tuple pointfree


Can the function createTuple below be expressed pointfree?

let createTuple = fun v -> (v, v*2)

createTuple 2 |> printfn "%A" // (2,4)

Solution

  • The F# library does not provide many functions for writing code in point-free style (mainly because it is not particularly idiomatic way of writing F#), so you cannot write your createTuple function using just what is available in the core library.

    If you really wanted to do this, you could define a couple of helper combinators for working with tuples:

    /// Duplicates any given value & returns a tuple with two copies of it
    let dup a = a, a
    /// Transforms the first element using given function
    let mapFst f (a, b) = (f a, b)
    /// Transforms the second element (not needed here, but adding for symmetry)
    let mapSnd f (a, b) = (a, f b)
    

    With these, you could implement your function in a point-free way:

    let createTuple = dup >> mapSnd ((*) 2)
    

    This does the same thing as your function. I think it is significantly harder to decipher what is going on here and I would never actually write that code, but that's another issue :-).