Advertisement
Guest User

Untitled

a guest
Aug 9th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE AllowAmbiguousTypes #-}
  2. {-# LANGUAGE ConstraintKinds     #-}
  3. {-# LANGUAGE DataKinds           #-}
  4. {-# LANGUAGE FlexibleContexts    #-}
  5. {-# LANGUAGE KindSignatures      #-}
  6. {-# LANGUAGE PolyKinds           #-}
  7. {-# LANGUAGE ScopedTypeVariables #-}
  8. {-# LANGUAGE TypeApplications    #-}
  9. {-# LANGUAGE TypeFamilies        #-}
  10. {-# LANGUAGE TypeOperators       #-}
  11.  
  12. import           Data.Kind
  13. import           Data.Proxy
  14. import           GHC.TypeLits
  15.  
  16. type family TypeId (tp :: k) :: Nat
  17.  
  18. type instance TypeId Int    = 1
  19. type instance TypeId String = 2
  20.  
  21. -- Fails:
  22. getTypeId :: forall tp . tp -> Int
  23. getTypeId _ = fromIntegral . natVal $ Proxy @ (TypeId tp)
  24.  
  25. -- main.hs:21:30: error:
  26. --     • No instance for (KnownNat (TypeId tp))
  27. --         arising from a use of ‘natVal’
  28. --     • In the second argument of ‘(.)’, namely ‘natVal’
  29. --       In the expression: fromIntegral . natVal
  30. --       In the expression: fromIntegral . natVal $ Proxy @(TypeId tp)
  31.  
  32. -- Works
  33. getTypeId' :: forall tp . KnownNat (TypeId tp) => tp -> Int
  34. getTypeId' _ = fromIntegral . natVal $ Proxy @ (TypeId tp)
  35.  
  36. main = do print (getTypeId (123     :: Int))
  37.           print (getTypeId ("hello" :: String))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement