ye9ane
ye9ane

Reputation: 2009

Adding a new constructor to a datatype after declaration

I have a requirement to add some new constructors to a datatype after it's module has been loaded. The pseudo code may seem like this:

import MyModule

data MyType = NewConstructor

In the above example MyType has been previously defined in MyModule. Is there a way to do that?

Upvotes: 1

Views: 158

Answers (1)

Nicolas
Nicolas

Reputation: 24769

You can't. A datatype is closed. And it is a good thing otherwise, how can you predict how previsouly defined function will behave?

Several workarounds exist, here are some off the top of my head:

  1. Use a function as a constructor. e.g. myExtendedType = MyType 42;
  2. Use your own type and a mapping function. e.g. data MyExtendedType = MyExtendedType; toMyType MyExtendedType = MyType 42;
  3. Wrap the existing datatype:

    import MyModule as Old
    
    data MyExtendedType = FromOld (MyType Int) | MyExtendedType
    
    foo (FromOld m) = Old.foo m
    foo MyExtendedType = undefined
    

Upvotes: 4

Related Questions