Skip to content

Instantly share code, notes, and snippets.

@mstksg
Created August 23, 2017 21:47
Show Gist options
  • Save mstksg/8768f5b5d012f5d6caf66d24d9960d04 to your computer and use it in GitHub Desktop.
Save mstksg/8768f5b5d012f5d6caf66d24d9960d04 to your computer and use it in GitHub Desktop.
reflection for dynamic Eq instances
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE UndecidableInstances #-}
import Data.Proxy
import Data.Reflection
data EqDict a = EQD { withEqDict :: a -> a -> Bool }
newtype HasEq s a = HasEq a
instance Reifies s (EqDict a) => Eq (HasEq s a) where
HasEq x == HasEq y = withEqDict (reflect (Proxy @s)) x y
eqBy :: (a -> a -> Bool) -> [a] -> [a] -> Bool
eqBy f xs ys = reify (EQD f) $ \(Proxy :: Proxy s) ->
map (HasEq @s) xs == map (HasEq @s) ys
main :: IO ()
main = print $ eqBy (==) [1..10] [1..10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment