Operator overloading in MLton
StandardML uses overloaded arithmetics operators, so its compilers support function overloading deep inside, but since it's not really a part of the language, they don't make the overloading mechanism available to the user.
MLton, however, doesn't try too hard at hiding it and it's fairly easy to figure it out by reading the source.
It doesn't mean you should be doing this in real code, but what can be abused for fun, will be abused.
We'll make a "^+" operator and make it mean addition for integers and concatenation for strings. To do it, we'll need two modules and some magic.
signature FOO = sig val ^+ : int * int -> int end structure Foo : FOO = struct val ^+ = fn (x, y) => x + y end signature BAR = sig val ^+ : string * string -> string end structure Bar : BAR = struct val ^+ = fn (x, y) => x ^ y end (* Magic begins here *) _overload ^+ : ('a * 'a -> 'a) as Foo.^+ and Bar.^+ (* Magic ends here *) infix 6 ^+ val () = print ("hello " ^+ "world\n") val () = print ((Int.toString (3 ^+ 4)) ^ "\n")
Now we need to compile it. Compiling with default options fails:
$ mlton ./test.sml Error: test.sml 17.1. _overload disallowed. compilation aborted: parseAndElaborate reported errors
We need another bit of magic:
mlton -default-ann 'allowOverload true' ./test.sml
Now it works:
$ ./test hello world 7












