Reputation: 709
Is it possible in ML to allow a variable in ML to have more than one type?
For instance, If I want a node in a tree to only be an int or a string.
Node of int * string
I tried this but it just results in a tuple type of (int, string). I don't want it to be a tuple, just either an int or a string. Is this allowed?
Upvotes: 3
Views: 567
Reputation: 11627
Just to generalise @TimDestan's great answer a bit: the general idea of a value having either one type or the other can be encoded in a type. E.g., in Haskell and Scala we have the Either
type which can hold values of two different types exclusively. We can define the same in SML:
datatype ('a, 'b) either = Left of 'a | Right of 'b
Now you can encode your node as:
Node of (int, string) either
And nodes can be constructed like:
Node (Left 1)
Node (Right "hello")
This is a bit more lightweight than defining a custom sum type for this case specifically.
Upvotes: 1
Reputation: 2028
As pointed out in a comment, the feature you're looking for is union types. I believe the syntax for them in SML is:
datatype Node = IntNode of int
| StringNode of string
Upvotes: 4