Skip to content

Instantly share code, notes, and snippets.

@msakai
Created May 28, 2023 01:28
Show Gist options
  • Save msakai/2253dee445eccf17025b77b040deecbb to your computer and use it in GitHub Desktop.
Save msakai/2253dee445eccf17025b77b040deecbb to your computer and use it in GitHub Desktop.
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module QueryInterface where
-- Maybe (GHC.Exts.DictBox a)
data QueryIntefaceResult a where
HasInterface :: a => QueryIntefaceResult a
NoInterface :: QueryIntefaceResult a
class QueryInterface a where
queryInterface :: QueryIntefaceResult a
instance QueryInterface (Fractional Double) where
queryInterface = HasInterface
instance QueryInterface (Integral Double) where
queryInterface = NoInterface
instance QueryInterface (Fractional Int) where
queryInterface = NoInterface
instance QueryInterface (Integral Int) where
queryInterface = HasInterface
instance QueryInterface (Fractional ()) where
queryInterface = NoInterface
instance QueryInterface (Integral ()) where
queryInterface = NoInterface
f :: forall a. (QueryInterface (Fractional a), QueryInterface (Integral a)) => a -> a
f x =
case queryInterface @ (Fractional a) of
HasInterface -> x / 2
NoInterface ->
case queryInterface @ (Integral a) of
HasInterface -> x `div` 2
NoInterface -> x
test :: IO ()
test = do
print $ f (100.0 :: Double) -- 50.0
print $ f (11 :: Int) -- 5
print $ f () -- ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment