Skip to content
Anonymous Functions and Pipelines
step 1/5

Reading — step 1 of 5

Learn

~1 min readFunctions

Anonymous functions with fun:

let double = fun x -> x * 2
let add = fun x y -> x + y

Function values are first-class — pass them to higher-order functions:

List.map (fun x -> x * 2) [1; 2; 3]    (* [2; 4; 6] *)
List.filter (fun x -> x > 2) [1; 2; 3]  (* [3] *)

|> is the pipe operator — feeds left value as last argument of right function:

[1; 2; 3; 4; 5]
|> List.filter (fun x -> x mod 2 = 0)
|> List.map (fun x -> x * x)
|> List.fold_left (+) 0
(* 20: filtered to evens, squared, summed *)

Without pipes you'd write right-to-left:

List.fold_left (+) 0 (List.map (fun x -> x * x) (List.filter (fun x -> x mod 2 = 0) [1;2;3;4;5]))

Pipes are how you write OCaml that reads top-to-bottom like a recipe.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…