Search code examples
ocamlcons

OCaml cons purpose


I'm reading through the language manual for OCaml and came across the "cons" operator, denoted as

::

However, it's not explained at all what it is, and what its typically used for.


Solution

  • This is the fundamental list structuring operator. The list [1; 2; 3] is constructed with three applications of the :: operator:

    $ ocaml
            OCaml version 4.01.0
    
    # 1 :: 2 :: 3 :: [];;
    - : int list = [1; 2; 3]
    

    (This operation has been called cons since the early Lisp days of 50 years ago.)

    The :: operator can also appear in patterns, to destructure a list:

    let rec length l =
        match l with
        | [] -> 0
        | h :: t -> 1 + length t