[Haskell-beginners] question on types

James Cook mokus at deepbondi.net
Fri Jul 29 16:58:46 CEST 2011


On Jul 29, 2011, at 9:49 AM, Jake Penton wrote:

> Well, there have been a couple of answers on this thread that suggest that a constraint/context will work. But this does not clear things up entirely for me. I probably do not understand your answer. But adding a constraint by itself does not of itself change things, although perhaps you are not suggesting that it would. 
> 
> For example, this does not compile:
> 
> f :: Fractional a => a
> f = 3.14

It should.  Is there something else in the file you're compiling which somehow conflicts?  What error does it print?

> This does:
> 
> class Foo a where
>     f :: Fractional a => a
> 
> instance Foo Float where
>     f = 3.14
> 
> So I infer that the reason that my example int the original post compiles is something other than merely the presence of the constraint. This compiles:
> 
> f :: Num a => a
> f = 1

Actually, it is solely the presence of the constraint which makes it OK.  By constraining it, you're saying "f can produce a value of any type, so long as that type implements Num" - and by saying that, you get to rely on the compiler enforcing it, so you can use all the functions Num provides.  One of those functions is "fromInteger", which the compiler uses in the implementation of "1".  When you say "f = 1", the compiler interprets that as "f = fromInteger (1 :: Integer)".  Without the constraint, you're not allowed to use "fromInteger" because that function doesn't exist for all types.

-- James
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110729/4b0e432c/attachment-0001.htm>


More information about the Beginners mailing list