Skip to content

@DanielSchuessler /SubsetVariants.hs
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Subset variants
{-# 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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.