Nested/Sub data types in haskell

Posted by Tom Carstens on Stack Overflow See other posts from Stack Overflow or by Tom Carstens
Published on 2012-12-17T05:01:12Z Indexed on 2012/12/17 5:03 UTC
Read the original article Hit count: 102

Filed under:
|

So what would be nice is if you could do something like the following (not necessarily with this format, just the general idea):

data Minor = MinorA | MinorB
data Major = Minor | MajorB

isMinor :: Major -> Bool
isMinor Minor = True
isMinor _ = False

So isMinor MinorA would report True (instead of an error.) At the moment you might do something like:

data Major = MinorA | MinorB | MajorB

isMinor :: Major -> Bool
isMinor MinorA = True
isMinor MinorB = True
isMinor _ = False

It's not terrible or anything, but it doesn't expand nicely (as in if Minor when up to MinorZ this would be terribly clunky). To avoid that problem you can wrap Minor:

data Minor = MinorA | MinorB
data Major = MajorA Minor | MajorB

isMinor :: Major -> Bool
isMinor (MajorA _) = True
isMinor _ = False

But now you have to make sure to wrap your Minors to use them as a Major... again not terrible; just doesn't really express the semantics I'd like very well (i.e. Major can be any Minor or MajorB). The first (legal) example is "Major can be MinorA..." but doesn't have any knowledge of Minor and the second is "Major can be MajorA that takes a Minor..."

p.s. No, this isn't really about anything concrete.

© Stack Overflow or respective owner

Related posts about haskell

Related posts about abstract-data-type