문제

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?

도움이 되었습니까?

해결책

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
    
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top