We all know that :t in ghci gives the type of an expression:
Prelude> :t [1..]
[1..] :: (Enum t, Num t) => [t]
What I need is an equivalent of :t in haskell script(I'll call it typeStr) :
main = putStrLn $ typeStr [1..]
that can print something like (Enum t, Num t) => [t] on screen.
Is that possible?
Yes, there are several ways.
1. Use dynamic typing
For the simple case of monomorphic types, you can use the Typeable instance:
Data.Dynamic> typeOf [1..]
[Integer]
2. Use runtime evaluation
However, to do this properly - to get the type of polymorphic values - you'll need the full GHC type checker. E.g. via the ghc-api library, and its nice wrapper, hint:
Language.Haskell.Interpreter> runInterpreter $ typeOf "[1..]"
Right "(P.Enum t, P.Num t) => [t]"
Which is the correctly inferred type using the full GHC type checker, invoked dynamically.
Yes, you can, as long as the type is an instance of Data.Typeable:
import Data.Typeable
typeStr :: Typeable a => a -> String
typeStr a = show $ typeOf a
I don't think you're going to get the most general type possible however, since the argument will be of a specific type. For instance, typeStr [1..] yields [Integer] in ghci.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With