Lesson 7 of 15

Higher-Order Functions

Higher-Order Functions

Functions in OCaml are first-class — they can be passed as arguments and returned from other functions.

Passing Functions

let apply f x = f x
let double x = x * 2

let () = print_int (apply double 5)   (* 10 *)

Anonymous Functions

let result = apply (fun x -> x + 10) 5   (* 15 *)

Composition

let compose f g x = f (g x)

let add1 x = x + 1
let double x = x * 2

let add1_then_double = compose double add1
let () = print_int (add1_then_double 3)   (* 8 *)

Your Task

Write a function apply_twice f x that applies f to x twice (i.e., f (f x)). Test it with a doubling function.

JS Transpiler loading...
Loading...
Click "Run" to execute your code.