Haskell constructor aliases

后端 未结 2 751
半阙折子戏
半阙折子戏 2020-12-06 19:48

Is there a way to have something equivalent to creating \"constructor aliases\" in Haskell? I\'m thinking similar to type aliases where you can give the type a different nam

相关标签:
2条回答
  • 2020-12-06 20:22

    Despite the drawbacks you mentioned, I strongly suggest simply creating a fresh ADT for your type; for example

    data TimeVariable = Constant UTCTime | Assigned UTCTime | Unassigned
    

    I offer these arguments:

    1. Having descriptive constructors will make your code -- both construction and pattern matching -- significantly more readable. Compare Unassigned and Right Nothing. Now add six months and do the same comparison.
    2. I suspect that as your application grows, you will find that this type needs to expand. Adding another constructor or another field to an existing constructor is much easier with a custom ADT, and it makes it very easy to identify code locations that need to be updated to deal with the new type.
    3. Probably there will not be quite as many sensible operations on this type as there are in the standard library for munging Either and Maybe values -- so I bet you won't be duplicating nearly as much code as you think. And though you may be duplicating some code, giving your functions descriptive names is valuable for the same readability and refactoring reasons that giving your constructors descriptive names is.
    4. I have personally written some code where all my sums were Either and all my products were (,). It was horrible. I could never remember which side of a sum meant which thing; when reading old code I had to constantly remind myself what conceptual type each value was supposed to be (e.g. Right doesn't tell you whether you're using Right here as part of a time variable or part of some other thing that you were too lazy to make an ADT for); I had to constantly mentally expand type aliases; etc. Learn from my pain. ;-)
    0 讨论(0)
  • 2020-12-06 20:33

    The 'pattern synonyms' might get merged into ghc: http://ghc.haskell.org/trac/ghc/ticket/5144. In the meantime there is also -XViewPatterns, which lets you write things like:

    type Timeslot = Either UTCTime (Maybe UTCTime)
    fieldA = either Just (const Nothing)
    fieldB = either (const Nothing) id
    
    
    f (fieldA -> Just time) = ...
    f (fieldB -> Just time) = ...
    f _ = ...
    
    0 讨论(0)
提交回复
热议问题