Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 37 ยท Functions and Pipelines

F# Pipelines and Function Composition: |>, >> and <<

Master the F# pipeline operator |> and composition operators >> and <<. Build readable data transformations, understand type inference flow, and compare pipelines with nested calls.

If one idea defines the F# style, it is the pipeline. Instead of nesting calls inside calls, you write data flowing from top to bottom, each step a small function. This lesson explains the pipe operator |>, why it helps type inference, the composition operators >> and <<, and how to design functions so they plug into pipelines.

The problem pipes solve

Without a pipe, a sequence of operations nests inside out:

FSHARP
let result = List.sum (List.map (fun n -> n * n) (List.filter (fun n -> n % 2 = 0) [ 1 .. 10 ]))

To read this you start in the middle, with the list, and work outward. A pipeline puts the steps in the order they happen:

FSHARP
let result =
    [ 1 .. 10 ]
    |> List.filter (fun n -> n % 2 = 0)
    |> List.map (fun n -> n * n)
    |> List.sum
// 220

Now it reads like a recipe: take 1 to 10, keep the evens, square, sum.

What |> does

The pipe operator is defined in the standard library as:

FSHARP
let (|>) x f = f x

That is all: it takes a value on the left and a function on the right and applies the function to the value. 5 |> square is square 5. Because functions in F# are curried (Currying and partial application), List.filter pred is a function waiting for a list, and the pipe supplies it.

flowchart LR
    A["[1..10]"] -->|filter even| B["[2;4;6;8;10]"]
    B -->|map square| C["[4;16;36;64;100]"]
    C -->|sum| D["220"]

Each step takes the previous result as its last argument.

Pipelines and type inference

Pipes also help the compiler. F# infers types from left to right, so when the data comes first, the compiler already knows its type when it reaches the lambda:

FSHARP
let lengths = [ "apple"; "kiwi" ] |> List.map (fun s -> s.Length)    // works
let broken = List.map (fun s -> s.Length) [ "apple"; "kiwi" ]       // error: type annotation needed

In the second line the lambda is checked before the list, so s.Length is a mystery. This is the second big reason, after readability, why library functions take the data last and F# code is piped.

Variants: ||> and |||> and <|

  • ||> pipes a pair into a function with two curried arguments: (1, 2) ||> add.
  • |||> does the same for triples.
  • <| is a reverse pipe: f <| x equals f x. It is used to avoid parentheses: printfn "%d" <| add 1 2. Use sparingly.
FSHARP
(3, 4) ||> fun a b -> a * b     // 12

Composition with >> and <<

The composition operators glue two functions together into a new function, without mentioning the argument:

FSHARP
let (>>) f g = fun x -> g (f x)

f >> g means "do f, then g". f << g means "do g, then f" (like mathematical composition).

FSHARP
let trim (s: string) = s.Trim()
let shout (s: string) = s.ToUpper()
let exclaim (s: string) = s + "!"

let clean = trim >> shout >> exclaim
clean "  hello  "        // "HELLO!"

clean is a new function: string -> string. You can reuse it anywhere a function is expected:

FSHARP
[ " a "; " b" ] |> List.map clean       // ["A!"; "B!"]

The types must line up: the output of the left function is the input of the right one.

Pipe versus compose

|> >>
Left side a value a function
Result a value a function
Use for running a computation now building a reusable step

A useful trick: a pipeline x |> f |> g is the same as x |> (f >> g).

Designing for pipelines

  1. Put the main data last in your own functions, so |> can feed it.
  2. Return a useful value, not unit, from each step.
  3. Keep steps small and named when a lambda gets long. Extract it into a function with a good name:
FSHARP
let isAdult person = person.Age >= 18
let fullName person = person.First + " " + person.Last

people
|> List.filter isAdult
|> List.map fullName
|> List.sort
  1. Debug a pipeline by inserting a printing step that returns its input unchanged:
FSHARP
let tap label x =
    printfn "%s: %A" label x
    x

[ 1 .. 5 ]
|> List.map (fun n -> n * 2)
|> tap "doubled"
|> List.sum

Another way is to select a prefix of the pipeline in your editor and send it to FSI.

Pipelines with strings and options

Pipes work with any function, not only lists:

FSHARP
"  The Quick Brown Fox "
|> fun s -> s.Trim()
|> fun s -> s.Split ' '
|> Array.map String.length
|> Array.sum

Option and Result values also have Option.map, Option.bind, Result.map that fit pipelines naturally, and they are covered in the options chapter.

A pipeline in C#: LINQ

LINQ's method chaining is the same idea, with the "pipe" being the dot. The first stand-in is the pipeline above. The second builds a composed function with Func, F#'s >>.

C# C# stand-in: a pipeline with LINQ

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# C# stand-in: composing functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is 5 |> square equivalent to?

    The pipe applies the function on the right to the value on the left.
  2. 2. Why is names |> List.map (fun s -> s.Length) accepted while List.map (fun s -> s.Length) names may fail?

    Type inference flows left to right, so the pipe tells the compiler the element type first.
  3. 3. What does f >> g produce?

    Composition builds a new function: first f, then g.
  4. 4. Which design helps your own functions work in pipelines?

    With the data last, data |> yourFunction config supplies it automatically.

Summary

  • x |> f is f x; pipelines read top to bottom and help type inference.
  • f >> g composes functions into a new function; |> runs a value through functions.
  • ||> and |||> pipe pairs and triples; <| is a reverse pipe.
  • Design functions with the data last, keep steps small, and use a tap function to debug.

Next: Recursion