Comments are useful text to describe code. These are ignored by the compiler during the compilation phase

Ocaml comments examples

There are three types of ocaml comments

  • Single Line Comments
  • Multi-Line Comments
  • Documentation Comments

Single-line comments

Single-line comments are written a single line that always starts with (* followed by space and text and ends with*)

(*single-line comment example*)

Multi-line comments example

Multi line comments starts with (* followed by each line preceded with * and ends with *)

These are also called block comments that span multiple lines.

(* Multi-line comments
* example1
* example2

Documentation Comments

Documentations comments are used to write a comment about classes, methods, and expressions for developers to understand the code. ocamldoc is a tool that outputs documentation for an OCaml code.

It outputs in HTML,Texinfo formats


(** Comment text *)

Here is an example to generate documentation comments in OCaml methods, functions, and class types.

(** function myfunc *)
let myfunc x y = x + y

(** employeetype *)
type employee = {
    id : int ;    (** Employee id*)
    name : string ; (** employee name *)
(** User class *)
class User =
      (** department instane variable *)
      val mutable department = "sales"
      (** properties *)
      val id = 11
      val name = "admin"
      (**  method getDepartment *)
      method getDepartment (value: string) = 1
    (** The below method does not show in  documentation *)
      method getSalary (value : int) = 1   

(**/**) are stop comments syntax, code after these comments does not show in documentation output

Here is a command syntax to generate documentation comments

ocamldoc options sourcefiles


ocamldoc -html

How do you write a comment in OCaml?

Comments can be single, multi-line, or documentation comments.

Single-line text included between (* and *) in one line. multi-line text included between (* and *) in multiple lines and each line prefixed with *.

Documentation comments are special comments that are included between (** and *) in multiple lines.