ocamlfunctorinfix-operator

Using infix operator in the module in OCaml


I am trying to define a SCALAR signature with its own infix operator in

module type SCALAR =
sig
  type t                               (* type of scalar element *)
       
  val zero : t 
  val one : t

  val (++) : t -> t -> t               (* infix addition: t ++ t *)
end

with using SCALAR signature, I defined a INT module:

module INT : SCALAR with type t = int
=
struct
  type t = int

  let zero = 0
  let one = 1

  let (++) x y = x + y
end

I expected adding two INT modules with defined infix operator like INT.zero ++ INT.one is valid operation and expected its returning value int = 1 but it raises error of "Unbounded value ++".

However, INT.(++) INT.zero INT.one worked correctly (with the return value I expected).

How can I use specific module's infix operator, without explicitly specifying module's name?


Solution

  • To use names from a module without mentioning the module, you need to open the module.

    Opening modules is something to avoid in many cases. For these cases you can use a local open:

    # let open INT in zero ++ one;;
    - : INT.t = 1
    # 
    

    Another form:

    # INT.(zero ++ one);;
    - : INT.t = 1
    # 
    

    You can also make a local synonym for INT.(++):

    # let (++) = INT.(++);;
    val ( ++ ) : INT.t -> INT.t -> INT.t = <fun>
    # INT.zero ++ INT.one;;
    - : INT.t = 1
    #