csslayer
csslayer

Reputation: 357

use non-default overloaded operator in smlnj

smlnj will make overloaded operator, like op + to use int by default, now I want to it returns a function in real * real -> real, how can I do in inline way?

"inline way" means not something like binding a new val:

fun add(x:real,y:real) = x + y;

If my memory is correct there is some grammar allows sml it to just do something like "cast" op + to real, but I can't really find it anywhere..

Upvotes: 1

Views: 800

Answers (3)

Andreas Rossberg
Andreas Rossberg

Reputation: 36098

You could declare

open Real

in the scope where you define the function, but I strongly advise against that. Type-annotating the function is the best way. You don't have to annotate every parameter, btw, it's enough to do one, or in this case, even the return type:

fun add(x : real, y) = x + y

fun add(x, y) : real = x + y

Upvotes: 0

Jesper.Reenberg
Jesper.Reenberg

Reputation: 5944

There are various ways that you can get SML to type op+ as the real counterpart.

Depending on what ever code you have,

  • You can as suggested, type annotate the surrounding function, thus enforcing the parameters to op+ to be of type real.

  • Since you are nonfixing the addition function (presumably for use as a higher order function?), you could just as well pass along the addition function from the real module Real.+

  • Or you could annotate it like this: op+ : real * real -> real, which is really ugly and stupid, considering you can use Real.+ instead. But it is an option.

Upvotes: 3

waldrumpus
waldrumpus

Reputation: 2590

If the default instance of the operator is not the one you need for your value's type, you can use type annotation on the operands to enforce the desired typing.

For example, while

val f = fn a => a + a

will be typed int -> int, this value

val g = fn a:real => a + a

will be typed real -> real.

Upvotes: 0

Related Questions