Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert expression into the string describing its type in haskell script?

Tags:

haskell

ghc

ghci

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?

like image 491
Javran Avatar asked Apr 15 '26 12:04

Javran


2 Answers

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.

like image 55
Don Stewart Avatar answered Apr 17 '26 04:04

Don Stewart


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.

like image 45
pat Avatar answered Apr 17 '26 03:04

pat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!