public
Last active

Subset variants

  • Download Gist
SubsetVariants.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
{-# LANGUAGE ScopedTypeVariables, GADTs, KindSignatures, MultiParamTypeClasses, FlexibleContexts #-}
 
data A
data B
data C
 
data SumABC :: (* -> *) where
A :: Int -> SumABC A
B :: Int -> SumABC B
C :: SumABC C
 
class Elem t set where
elemPrf :: set t
 
-- | Represents the set {A,B}
data AB :: (* -> *) where
AB_A :: AB A
AB_B :: AB B
 
instance Elem A AB where elemPrf = AB_A
instance Elem B AB where elemPrf = AB_B
 
unAB :: forall t. Elem t AB => SumABC t -> Int
unAB x = case elemPrf :: AB t of
AB_A -> case x of
A i -> i
AB_B -> case x of
B i -> i
 
-- Alternative without scoped type variables
 
-- | Type inference helper
elemPrf' :: Elem t set => f t -> set t
elemPrf' = const elemPrf
 
-- Same type as unAB
unAB' x = case elemPrf' x of
AB_A -> case x of
A i -> i
AB_B -> case x of
B i -> i
 
main = print (unAB' (A 1), unAB' (B 2))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.