[Haskell-cafe] Managing a sum type with a lot of constructors

Michael Burge michaelburge at pobox.com
Thu Aug 24 01:45:13 UTC 2017


If you have that many constructors, you probably aren't pattern-matching
against the whole thing everywhere. So you could extract the few functions
that use the entire type for case analysis into a typeclass, make each
constructor its own type, and implement the typeclass:

Instead of:

something :: A -> IO ()
something A1 = putStrLn "hello"
something (A2 _) = putStrLn "world"

Use:

data A1
data A2 = A2 Int

class RelatedConst a of
  something :: a -> IO ()

instance RelatedConst A1 where
  something _ = putStrLn "hello"

instance RelatedConst A2 where
  something _ = putStrLn "world"

Then, each declaration and instance could go in its own file.

If on the other hand, you are using lots of partial case matches
everywhere, see if there are commonalities and extract a typeclass for each
group


On Wed, Aug 23, 2017 at 6:29 PM, Adam Flott <adam at adamflott.com> wrote:

> I have a sum type with a lot of constructors and I'm not sure how to
> represent
> the type with maintainability in mind. For example,
>
>     data A = A1
>            | A2 Int
>            | A3 Text Int32 Bool
>            | ...
>            | A100 Bool
>
> Every inner type is concrete. There are 100+ constructors with no sign of
> ever
> getting reduced.
>
> What technique would you recommend to keep the sum type approach but not
> having
> to define them all in one spot? I'm thinking 1 inner type + 1 function to
> construct per file (if that's possible).
> _______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20170823/c47aeffa/attachment.html>


More information about the Haskell-Cafe mailing list