typestar

Composition and @@ in OCaml

Build functions from functions; @@ drops the last parens.

(* @@ applies without parentheses; composition is a one-liner away. *)
let compose f g x = f (g x)

let cm_of_m m = m *. 100.0
let readable cm = Printf.sprintf "%.0f cm" cm
let describe = compose readable cm_of_m

let () =
  print_endline (describe 0.65);
  print_endline (describe 1.2);
  (* @@ saves the closing paren on the last argument. *)
  print_endline @@ describe 0.08;
  Printf.printf "Deep end: %s\n" @@ readable @@ cm_of_m 1.5

How it works

  1. compose f g x = f (g x) is the whole definition.
  2. The composed describe applies like any function.
  3. print_endline @@ describe 0.08 saves the wrapping parens.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
428
Tokens
84
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 3 of 4 in Functions, step 6 of 29 in Language basics.

← Previous Next →