Haskell: Print type of variable within function

Viewed 360

How do I print the type of a variable within a function in an .hs file?

From ghci, I can do :type var. How do I do something like the following:

sumList :: [Int] -> Int
sumList [] = 0
sumList (h:t) = traceShow (type h) $ h : sumList t

Which would print something like h::Int at every recursive iteration?

1 Answers

You can work with typeOf :: forall a. Typeable a => a -> TypeRep for all the types that are an instance of the Typeable typeclass:

import Data.Typeable(typeOf)

sumList :: [Int] -> Int
sumList = foldr (\h -> traceShow (typeOf h) (h+)) 0

of course for the given sumList function it will always return Int, since that is the type of of the items in the list.

Since Haskell has full type erasure there is no such thing like Java's instanceof that can determine a reference to the type at runtime: since the compiler knows all the necessary types at compile time, the objects are not "tagged" with the corresponding type.

Related