2
votes

I'm trying to write a function to check for type equality, ignoring instance variables (not sure if that's the right terminology for SML). Preferably, this function could operate on multiple datatypes.

So, if I have:

datatype D = A | B of int;

myEqual A A, myEqual (B 1) (B 1), and myEqual (B 1) (B 2) would all return true, and myEqual A (B 1) would return false.

My first thought was to implement it as something like fun myEqual a b = a = b;. However, this compares the instance variables of both variables, which is not what I want, so myEqual (B 1) (B 2) would return false.

I know that this could be implemented in this case by using pattern matching like

fun myEqual (B _) (B _) = true
  | myEqual A A = true
  | myEqual _ _ = false;

But this only works for this specific datatype.

Are there any operations in SML to check only for type equality, but not instance variables?

1

1 Answers

4
votes

First of all, datatype D = A | B of int; is just one type with two branches. So what you compare is a comparison of different forms in different branches. I think you have to decompose datatypes in order to write such comparison functions. Therefore, writing a myEqual function for each datatype is natural.

Second, if you want to talk about two independent datatypes, it doesn't make sense to have that kind of comparison. Since SML is static and strong typing, you know the specific type of each variable at compile time.