Lesson 14 of 15

Modules

Modules

OCaml's module system organizes code into namespaced units. You have already been using modules like List and String:

List.length [1; 2; 3]     (* 3 *)
String.length "hello"     (* 5 *)

Defining Modules

module Math = struct
  let pi = 3.14159
  let square x = x * x
end

let () = print_int (Math.square 5)

Module Signatures

Signatures define the interface:

module type STACK = sig
  type 'a t
  val empty : 'a t
  val push : 'a -> 'a t -> 'a t
  val pop : 'a t -> 'a t
end

Practicing the Pattern

Since our runtime uses a simplified OCaml subset, we will practice the module concept by building a small "stack" library using lists and functions — the same approach modules use internally.

Your Task

Implement a stack using lists: stack_empty, stack_push, stack_pop, stack_top, and stack_size.

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