Overload in Ocaml

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

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

Which one will work?

+5
source share
1 answer

It all depends on what you mean by overload. There are several use cases, for example:

If you want to use the regular name of the infix operators in a mathematical expression, manipulating something other than integers: reinstall your operators locally; modules and "local open" can help with this.

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

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

, , . , ( ), ..

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.)

, , , , "" ( , ), - , Haskell .

+13

All Articles