DEV Community

Brian Berns
Brian Berns

Posted on

F# Tip 2: Use the pipe operator

F#'s pipe operator |> lets you chain function calls together easily:

let car =
    Car.create Red
        |> Car.drive 10000
        |> Car.paint White
Enter fullscreen mode Exit fullscreen mode

This creates a red car, drives it 10000 miles, and then paints it white. If you're familiar with "fluent" coding in C#, you'll see a strong similarity:

// C#
var car =
    new Car(Color.Red)
        .Drive(10000)
        .Paint(Color.White);
Enter fullscreen mode Exit fullscreen mode

Note that the pipe operator leverages partial function application. For example, the Car.drive function takes two arguments:

let drive miles car =
    { car with Mileage = car.Mileage + miles }
Enter fullscreen mode Exit fullscreen mode

When we call it using the pipe operator, we specify all the arguments except the last one, and then invoke the resulting "curried" function with the pipe operator:

car |> Car.drive 50
Enter fullscreen mode Exit fullscreen mode

When designing an F# API, it's important to put the "primary" argument last in the function signatures. For example, we collect all Car-oriented functions in a Car module, and list the car argument last in each one:

module Car =

    let create color =
        { Mileage = 0; Color = color }

    let drive miles car =
        { car with Mileage = car.Mileage + miles }

    let paint color car =
        { car with Color = color }
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
saint4eva profile image
saint4eva • Edited

Nice tutorial. I have a question. Why not this:

var car = new Car(Color.Red)
.Drive(10000)
.Paint(Color.White);

Instead of this:

var car =
new Car(Color.Red)
.Drive(10000)
.Paint(Color.White);

Collapse
 
shimmer profile image
Brian Berns • Edited

You’re right, that would probably be better for C#. I added a carriage return to emphasize the similarity with the F# syntax (which requires the carriage return).

Collapse
 
saint4eva profile image
saint4eva

okay.