0
votes

I want to ask the user to input a variable and check it is real or integer and take two different operations for corresponding actions. Say true if integer else false;

fun realorinteger(n)= if n=int then true else false;

but it definitely does not work. I tried if n in int as well.

Any help?

1

1 Answers

2
votes

You cannot do this.

The type system simply doesn't allow a function to take multiple different types, and act according to which type it is. Either your function takes an int, or it takes a real. (Or it takes both, but can also take strings, lists, etc... ie. is polymorphic)

You could fake it by making a datatype, which encapsulates values that can be either integers or reals, like so:

datatype intorreal = IVal of int | RVal of real

You can then use pattern matching on such a value to extract the desired number:

fun realorinteger (IVal i) = ... (* integer case here *)
  | realorinteger (RVal r) = ... (* real case here *)

This function will then have the type intorreal -> x, where x is the type of the right-hand-side expressions. Note, the resulting value must be of the same type in both cases.

An example of such a function could be a rounding function:

fun round (IVal i) = i
  | round (RVal r) = Real.round r

Which is then called like so:

val roundedInt  = round (IVal 6);
val roundedReal = round (RVal 87.2);