8

I know that OCaml does not support overloading. Then, instead of overloading, what can we do to work this around?

1) use polymorphism instead? 2) give different functions different names? 3) put functions of the same name in different modules?

Which one will work?

user1382007
  • 81
  • 1
  • 3

1 Answers1

18

It all depends on what you mean by overloading. There are several use cases, such as:

If you want to use the usual infix operators name in a mathematical expression manipulating something else than integers: rebind your operators locally; modules and "local open" can help with that.

module I32 = struct
  open Int32
  let (+), (-), ( * ), (/), (!!) = add, sub, mul, div, of_int
end

 ... I32.(x + y * !!2) ...

If you want an operation to be polymorphic in the type of numeric type being used, you need to abstract over such numeric operators. For example the generic fast exponentiation function (by an integer), that can be used on matrices etc.

let rec pow ( * ) one a = function
  | 0 -> one
  | n -> pow ( * ) (if n mod 2 = 0 then one else one * a) (a * a) (n / 2)

let () = assert (pow ( *.) 1. 2. 3 = 8.)

More generally, yes, the idea is to capture what you want to "overload" on as a set of operators (here infix operators but plain names are fine and often better for readability), and pass around and abstract over dictionaries of those operations -- much like what Haskell type classes are compiled to, in fact.

gasche
  • 31,259
  • 3
  • 78
  • 100
  • I notice you did an 'open Int32' there in module I32, what would be different if you had done an 'include Int32' there instead? Are they essentially equivalent in that context? – aneccodeal May 08 '12 at 23:13
  • 1
    @aneccodeal: that would be very different: if I used `include`, this `I32` would include all of `Int32`, so opening `I32` locally would in particular import all definitions of `Int32`. I prefer not to `open` big scopes because it risks shadowing user definitions. – gasche May 09 '12 at 04:51