Hacker News new | ask | show | jobs
by greenavocado 809 days ago
OCaml's type system allows for expressing complex data structures and behaviors in a concise and readable manner. These types can significantly improve code clarity by providing explicit declarations of intent and structure. Here are some examples:

  type 'a binary_tree =
    | Leaf
    | Node of 'a binary_tree * 'a * 'a binary_tree

  type http_response = [
    | `Ok of string
    | `Error of int
    | `Redirect of string
  ]

  module type QUEUE = sig
    type 'a t
    exception Empty
    val empty: unit -> 'a t
    val enqueue: 'a -> 'a t -> 'a t
    val dequeue: 'a t -> 'a option * 'a t
  end

  type _ expr =
    | Int : int -> int expr
    | Bool : bool -> bool expr
    | If : bool expr * 'a expr * 'a expr -> 'a expr

  type person = {
    name: string;
    age: int;
    address: string; 
  }