Created
February 6, 2022 03:39
-
-
Save steshaw/5f1c696eceff17f7f21ddade4a53049e to your computer and use it in GitHub Desktop.
This file contains 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
-- See https://travis.athougies.net/posts/2017-04-26-close-the-world.html | |
{-# OPTIONS_GHC -fprint-explicit-foralls #-} | |
{-# LANGUAGE TypeApplications #-} | |
import Data.Maybe | |
import Data.Typeable | |
data Dyn where | |
Dyn :: (Show a, Typeable a) => a -> Dyn | |
x1, x2, x3 :: Dyn | |
x1 = Dyn (3 :: Int) | |
x2 = Dyn "Fred" | |
x3 = Dyn (Just (0 :: Integer)) | |
xs :: [Dyn] | |
xs = [x1, x2, x3] | |
is :: forall a. Typeable a => Dyn -> Maybe a | |
is (Dyn a) = cast a | |
only :: forall a. Typeable a => [Dyn] -> [a] | |
only = mapMaybe (\(Dyn x) -> cast x) | |
main :: IO () | |
main = do | |
print $ map (is @Int) xs | |
print $ mapMaybe (is @Int) xs | |
print $ only @Int xs | |
print $ only @String xs | |
print $ only @(Maybe Integer) xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment