F#'s pipe operator |>
lets you chain function calls together easily:
let car =
Car.create Red
|> Car.drive 10000
|> Car.paint White
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);
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 }
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
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 }
Top comments (3)
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);
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).
okay.