Skip to content

Instantly share code, notes, and snippets.

@steshaw
Created February 6, 2022 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save steshaw/5f1c696eceff17f7f21ddade4a53049e to your computer and use it in GitHub Desktop.
Save steshaw/5f1c696eceff17f7f21ddade4a53049e to your computer and use it in GitHub Desktop.
-- 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