Created
July 6, 2025 23:26
-
-
Save axionbuster/cfa306fbfb7d85e974066ac34672235f to your computer and use it in GitHub Desktop.
POC: Existentially-quantified type classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- | Demonstration of an existentially-qualified type class | |
| module Main (main) where | |
| import Data.Constraint (Dict (Dict)) -- constraints | |
| import Data.Kind (Type, Constraint) -- base | |
| -- A variant that contains a constraint and a term of unknown type. | |
| data Z (c :: Type -> Constraint) | |
| = forall t. ZY (Dict (c t)) t | |
| | forall t. ZN t | |
| -- Simpler variant that only carries a constraint | |
| data W (c :: Constraint) = WY (Dict c) | WN | |
| -- | Show if possible, determined dynamically. | |
| sz :: Z Show -> String | |
| sz (ZY Dict x) = show x | |
| sz (ZN _) = "<<unshowable>>" | |
| -- | | |
| -- @ | |
| -- >>> main | |
| -- ["2","()","<<unshowable>>"] | |
| -- @ | |
| main :: IO () | |
| main = do | |
| let zs :: [Z Show] = | |
| [ ZY Dict (2 :: Int) | |
| , ZY Dict () | |
| , ZN (const :: Int -> Int -> Int) | |
| ] | |
| print . map sz $ zs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment