typeOf raises Error

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

typeOf raises Error

Frank Schwidom
Hi,

if im calling (on the console)

"typeOf 1"

after importing Data.Typeable, i will gain

"Integer", as i expected, but if i do so in code which is
to compile, then there raises an error

------------
import Data.Typeable

main=
 print (typeOf 1)
------------

$ ghc -c DT.hs

$ ghc -c DT.hs

DT.hs:4:15:
    Ambiguous type variable `t' in the constraints:
      `Num t' arising from the literal `1' at DT.hs:4:15
      `Typeable t' arising from a use of `typeOf' at DT.hs:4:8-15
    Probable fix: add a type signature that fixes these type variable(s)

what can i do, to solve this problem?

Regards

Reply | Threaded
Open this post in threaded view
|

typeOf raises Error

Brandon S Allbery KF8NH
On 2009 Jan 11, at 5:27, Frank Schwidom wrote:
> "Integer", as i expected, but if i do so in code which is
> to compile, then there raises an error


Yes.  Numeric literals like 5 are actually read as (fromIntegral 5);  
then ghci applies defaulting to reduce it to Integer.  When compiled,  
you must resolve the polymorphism yourself.

--
brandon s. allbery [solaris,freebsd,perl,pugs,haskell] [hidden email]
system administrator [openafs,heimdal,too many hats] [hidden email]
electrical and computer engineering, carnegie mellon university    KF8NH


Reply | Threaded
Open this post in threaded view
|

typeOf raises Error

Brent Yorgey-2
In reply to this post by Frank Schwidom
As Brandon explained, since 1 is polymorphic, and print is polymorphic
in its argument, the compiler doesn't know which type to choose.  You
could fix it, for example, like this:

> ------------
> import Data.Typeable
>
> main=
>  print (typeOf (1 :: Integer))
> ------------

You might protest, what is the point of using typeOf if you have to
actually put in the type annotation anyway?  Well, this is a rather
contrived example; usually in a real program GHC would be able to
infer the type and an annotation would be unnecessary.

-Brent