Search code examples
smlml

datatype Nt = int | string in ML


When I only have datatype Nt = int | string, sml doesn't complain. But when I also have val n = 6 : Nt, ml doesn't accept 6 as an Nt. Why is this? I do know that, normally there should be data constructers before int and string, but here I'm having that to define functions that can take either int or string.


Solution

  • You are misinterpreting the code. To be clear, you cannot define datatypes without constructors. But ML has different name spaces for types and values. The occurrences of int and string in your example are value identifiers. As such, they just define new nullary constructors, and have absolutely zero to do with the types of the same name. You can now define val n = int : Nt. It is as if you had written datatype Nt = foo | bar.