[Haskell-cafe] selectively allow alternatives in a sum type

Henning Thielemann lemming at henning-thielemann.de
Tue Aug 30 14:46:26 UTC 2022


On Tue, 30 Aug 2022, Olaf Klinke wrote:

> Is there prior art/existing packages for the following? Is it maybefunctional programming folklore? Is it a sign of bad program design? 
> Sometimes I feel the need to selectively allow or disallow alternatives
> in a sum type. That is, suppose we have a sum type
>
> data Foo = LeftFoo !A | RightFoo !B
>
> and at some places in the program we want the type system to enforce
> that only the constructor LeftFoo can be used.

We could use a type variable and type classes.

f :: (ContainsA x) => ... x ...
g :: (ContainsA x, ContainsB x) => ... x ...

where the classes ContainsA and ContainsB provide accessors to the 
summands. Then x could be either A or B or Either A B and so on and there 
would be instances

instance ContainsA A
instance ContainsB B
instance (a ~ A) => ContainsA (Either a b)
instance (b ~ B) => ContainsB (Either a b)


More information about the Haskell-Cafe mailing list