Search code examples
ocamlinternals

Why is 'assert' not considered as a function of type bool->unit, but a keyword?


I do not follow why assert is not considered as a function of type bool -> unit, but a keyword.

# assert (2=2) ;;
- : unit = ()
# assert;;
Line 1, characters 6-8:
Error: Syntax error

Solution

  • This is required by the two-words keyword:

    assert false
    

    which has type 'a rather than unit.

    This is especially useful when using assert false to mock function

    let not_yet_implemented _ = assert false
    

    or when stating that a branch of a pattern matching is unreachable due to an invariant:

    let f = function
    | A | B as x ->
      begin match x with
      | A -> 1
      | B -> 2
      | C -> assert false
      end
    | C -> 2