Skip to content

Instantly share code, notes, and snippets.

@monadplus
Created October 1, 2019 14:27
Show Gist options
  • Save monadplus/344e6a88e295dbf40b1714cefbd58f05 to your computer and use it in GitHub Desktop.
Save monadplus/344e6a88e295dbf40b1714cefbd58f05 to your computer and use it in GitHub Desktop.
Reflect library in Haskell (there will be probably better ways to do this)
{-# LANGUAGE Rank2Types, FlexibleContexts, UndecidableInstances #-}
import Data.Reflection
import Data.Proxy
import Text.Printf
import Prelude
data Coin = Euro | USD
newtype Amount coin = Amount { _amount :: Int }
instance Reifies coin Coin => Show (Amount coin) where
show a@(Amount amount) =
case reflect a of
Euro -> printf "%.2f euros" (fromIntegral amount * 1.0 :: Double)
USD -> printf "%.2f usd" (fromIntegral amount * 0.9 :: Double)
likeProxy :: Proxy coin -> Amount coin -> Amount coin
likeProxy _ = id
printDivisa :: Coin -> String
printDivisa coin = reify coin $ \proxy ->
-- The lifted type can't scape this closure.
show $ likeProxy proxy (Amount 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment