Skip to content

Instantly share code, notes, and snippets.

@Javran
Created August 26, 2022 05:21
Show Gist options
  • Save Javran/a5ef97a3e55f66a901692308b981a612 to your computer and use it in GitHub Desktop.
Save Javran/a5ef97a3e55f66a901692308b981a612 to your computer and use it in GitHub Desktop.
Having some fun with https://hackage.haskell.org/package/typerep-map, can sorta carry around instances like this, caveat being keys have to be concrete ofc.
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module Main where
import qualified Data.TypeRepMap as TM
import Data.Typeable
data Shower a = Sf (a -> String)
type InstDict = TM.TypeRepMap Shower
instDict :: InstDict
instDict =
TM.insert (Sf (\(_ :: Int -> Double) -> "a function from Int to Double")) $
TM.insert (Sf $ show @String) $
TM.insert (Sf $ show @Int) mempty
showy :: forall a. Typeable a => a -> String
showy v = case TM.lookup @a instDict of
Nothing -> "<missing instance>"
Just (Sf f) -> f v
main :: IO ()
main = do
putStrLn $ showy (1 :: Int)
putStrLn $ showy (2 :: Double)
putStrLn $ showy ("Ahhh" :: String)
putStrLn $ showy (realToFrac @Int @Double)
putStrLn $ showy (id @Int)
{-
output:
1
<missing instance>
"Ahhh"
a function from Int to Double
<missing instance>
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment