OCaml Pipelines and Composition
Data processing often means "take this value, do A, then B, then C". Nested calls such as c (b (a x)) read inside-out. OCaml's pipe operator |> lets you write the steps in the order they happen.
The pipe operator |>
x |> f means f x. It is defined in the standard library as simply let ( |> ) x f = f x.
let () =
let words = [ "banana"; "Apple"; "cherry"; "apple"; "date" ] in
(* nested style: read from the inside out *)
let nested = String.concat ", " (List.sort_uniq compare (List.map String.lowercase_ascii words)) in
(* pipeline style: read from top to bottom *)
let piped =
words
|> List.map String.lowercase_ascii
|> List.sort_uniq compare
|> String.concat ", "
in
print_endline nested;
print_endline pipedapple, banana, cherry, date
apple, banana, cherry, date
The two versions do the same work. The pipeline reads like a recipe.
Pipes and partial application
Pipes work because of currying. In words |> List.map String.lowercase_ascii, the expression List.map String.lowercase_ascii is a partially applied function waiting for the list. This is why the standard library puts the data argument last in most functions (List.map f lst, List.filter p lst, String.concat sep lst).
let () =
[ 4; 9; 2; 7; 12; 5 ]
|> List.filter (fun n -> n mod 2 = 1) (* keep odd numbers *)
|> List.map (fun n -> n * n) (* square them *)
|> List.fold_left ( + ) 0 (* add them up *)
|> Printf.printf "sum of odd squares: %d\n"sum of odd squares: 155
9*9 + 7*7 + 5*5 = 81 + 49 + 25 = 155.
The application operator @@
f @@ x also means f x, but @@ has very low precedence and associates to the right. It saves parentheses around a long last argument:
let () =
print_endline @@ String.concat "-" @@ List.map string_of_int [ 2026; 10; 17 ];
(* same as: print_endline (String.concat "-" (List.map string_of_int [2026; 10; 17])) *)
Printf.printf "%d\n" @@ List.length @@ List.init 5 Fun.id2026-10-17
5
Use @@ sparingly; |> is usually clearer.
Function composition
Sometimes you want to build the pipeline as a function first and apply it later. Write a composition operator, or use Fun.compose (which applies the right-hand function first):
let ( >> ) f g x = g (f x) (* left-to-right composition *)
let slugify =
String.trim
>> String.lowercase_ascii
>> String.map (fun c -> if c = ' ' then '-' else c)
let shout = Fun.compose (fun s -> s ^ "!") String.uppercase_ascii
let () =
print_endline (slugify " Learn OCaml Today ");
print_endline (shout "hello")learn-ocaml-today
HELLO!
>> is not in the standard library, but many codebases define it. Defining your own operators is fine, as long as they stay readable.
Debugging a pipeline
You can insert a step that prints the intermediate value and passes it through unchanged:
let tap label lst =
Printf.printf "%s: [%s]\n" label (String.concat "; " (List.map string_of_int lst));
lst
let () =
[ 5; 3; 8; 1 ]
|> tap "input"
|> List.sort compare
|> tap "sorted"
|> List.map (fun x -> x * 10)
|> tap "scaled"
|> ignoreinput: [5; 3; 8; 1]
sorted: [1; 3; 5; 8]
scaled: [10; 30; 50; 80]
ignore throws away a value and returns (). It is needed here because the end of a let () = must be unit.
Test yourself
What does 3 |> fun x -> x * 2 evaluate to?
36- A function
- A type error
Why do most standard library functions take the data argument last?
- Tradition only
- So they can be partially applied and used in
|>pipelines - For performance
- Because of the garbage collector
What does ignore do?
- Skips the next line
- Discards its argument and returns
() - Catches exceptions
- Comments out code