[Haskell-cafe] why typeRepArgs (typeOf "hello") is [Char] ?

Brandon S. Allbery KF8NH allbery at ece.cmu.edu
Mon Feb 2 21:32:13 EST 2009


On 2009 Feb 2, at 15:27, minh thu wrote:
> Thanks. Could you add to your explanation this one :
>
> *Graph> typeRepArgs (typeOf (+))
> [Integer,Integer -> Integer]

The actual representation of an n-argument function in Haskell is a  
single-argument function that returns an (n-1)-argument function.   
(Technically, Haskell function applications are uncurried.)  This is  
reflected in typing by (->) being right associative:

 > (+) :: Num a => a -> a -> a :: Num a => a -> (a -> a)

the former being how we usually think about it and the latter being  
how Haskell actually sees it.  The typeRepArgs of (+) are set by this  
and by defaulting due to the monomorphism restriction to give you  
[Integer,Integer -> Integer] which corresponds to

 > (+) :: Integer -> (Integer -> Integer) :: Integer -> Integer ->  
Integer

which is the previous definition, swapping the internal and external  
forms and filling in Integer for (Num a =>) a via defaulting.

> In fact, I tried to write a function that would give the types used by
> a function,
> for instance [Integer, Integer, Integer] for (+) (the last one would
> be the 'return' type).
> So I applied recursively typeRepArgs to the second element of the list
> (if any) (here, Integer -> Integer).
>
> It worked well until I tried it on a function like :: Char -> Int ->
> [Char] where
> the last recursive call gives [Char] instead of [].

To get information about higher-kinded types, you want typeRepTyCon:

> Prelude Data.Typeable> typeRepTyCon (typeOf (+))
> ->

which is how you should determine that you want to deconstruct a  
function type.

Or for the final argument in your case:

> Prelude Data.Typeable> typeRepTyCon (typeOf "foo")
> []


There's the [] you wanted.  typeRepArgs then informs us that the tycon  
[] is applied to a sing;e type argument:

> Prelude Data.Typeable> typeRepArgs (typeOf "foo")
> [Char]


so the final argument type is ([] Char) (better known as [Char]).  The  
fact that it comes out as [Char] may be confusing you; the length of  
the list represents the number of type arguments the tycon takes, so  
you've been given a Char and need typeRepTyCon to get the rest of the  
story.

-- 
brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university    KF8NH


-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 195 bytes
Desc: This is a digitally signed message part
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20090202/c71dc9e2/PGP.bin


More information about the Haskell-Cafe mailing list