Discriminated type unions

Viewed 197

Is there a way to mimic TypeScript's discriminated type unions in Haskell? I want to do the following:

data A = B | C | D
data W = X | Y | Z

data FinalType = A | W

I know the last definition will create two value constructors A and W for FinalType. I can make the FinalType correctly in the following way right now:

data FinalType = B | C | D | X | Y | Z

But this isn't very neat and gets annoying after a lot of value constructors are added. Is there a way to mitigate this in Haskell?

1 Answers

As Robin Zigmond suggested,

data FinalType = A A | W W

will work. This takes on values like A B, A C, and W Z. Unless you need laziness here (relatively unlikely), you should probably make the constructors strict:

data FinalType = A !A | W !W

This way, calculating a value of type FinalType is guaranteed to calculate its actual contents.

Note that unlike Typescript's union types, Haskell's sum types are always discriminated. That's the role the A and W constructors play here, instead of having a common field to indicate which type is in use. A beginner may be confused by the overloading of the A and W names; you could be more explicit by instead defining

data FinalType = FinalA A | FinalW W
Related