Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading in Ocaml

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?

like image 999
user1382007 Avatar asked May 08 '12 12:05

user1382007


1 Answers

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.

like image 147
gasche Avatar answered Sep 23 '22 05:09

gasche