Question

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?

Was it helpful?

Solution

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
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top