Is there a function in Haskell that returns the type of its argument (or a string showing the type)?

typeOf is the canonical way to do this. Beware that it doesn't (can't) handle polymorphism as well as tools outside the language can.

Data.Typeable> typeOf ()
()
Data.Typeable> typeOf "hi"
[Char]
Data.Typeable> typeOf 3 -- hmmm....
Integer
Data.Typeable> typeOf id -- HMMMMMM...
<interactive>:4:1: error:
    • No instance for (Typeable a0) arising from a use of ‘typeOf’
    • In the expression: typeOf id
      In an equation for ‘it’: it = typeOf id

This is not something that Haskell programmers commonly want or need. So if you want this feature, you are doing something unusual. This can be because you are a beginner and still getting used to program in Haskell (in that case – what are you trying to achieve?). Or you are beyond beginner and want to experiment with unusual feature (in that case – read on).

  • If you are looking for a function that takes a String, interprets it as a Haskell term type-checks it and gives you its string, then you can embedd the Haskell compiler in your program. Look at the hint library.

  • If you are in a polymorphic context and want, maybe for debugging, know the type that some type variable a is bound to, then the Typeable type class can provide you this information: show (typeOf x) gives you the concrete type of the value referenced by the term x. You may have to add Typeable a constraints to your polymorphic function.

Tags:

Haskell