Lesson 15 of 15

Functors Overview

Functors

A functor in OCaml is a module that takes another module as a parameter — essentially a function from modules to modules.

module type COMPARABLE = sig
  type t
  val compare : t -> t -> int
end

module MakeSorter (C : COMPARABLE) = struct
  let sort lst = List.sort C.compare lst
end

You then instantiate it:

module IntSorter = MakeSorter(struct
  type t = int
  let compare a b = a - b
end)

The Functor Pattern

The key idea is abstraction over behavior: you write generic code that works with any module matching a signature. This is similar to generics in other languages but operates at the module level.

Practicing the Pattern

We can express the functor concept using higher-order functions — pass a comparison function to create specialized sort/search operations.

Your Task

Write a function make_sorter that takes a comparison function and returns a sorting function. Then use it to create sort_asc and sort_desc.

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