[Haskell-cafe] Are casts required?
daniel.is.fischer at googlemail.com
Mon Jun 6 11:37:50 CEST 2011
On Montag, 6. Juni 2011, 11:08, Ryan Ingram wrote:
> > Hi Pat. There aren't any casts in that code. There are type
> > annotations, but this is different than the idea of a cast like in C.
> > For example
> > ((3 :: Integer) :: Int)
> > is a compile error.
> > What you are seeing is that 3 has the type (forall a. Num a => a);
> > that is, the literal '3' gets converted by the compiler into
> > fromInteger (I# 3#)
> > where 3# represents the machine word '3' and I# is the internal
> > constructor Word# -> Integer.
Close, but not correct. In GHC, we have
data Int = I# Int#
and (if we're using integer-gmp)
= S# Int#
| J# Int# ByteArray#
So, 3# is the *signed* machine int '3' and you'd get
fromInteger (S# 3#)
using the literal '3'.
> > class Num a where
> > ...
> > fromInteger :: Integer -> a
> > So by 'casting', or rather, providing a type annotation, you are
> > specifying what instance of Num gets the call to 'fromInteger'.
> > As to whether you need a type annotation: it depends. For example:
> > foo () = sameId newId 3
Types don't match,
sameId :: IDs i => i -> i -> Bool
newId :: IDs i => i -> i
foo () = startId
to get Ryan's types.
> > the compiler will infer the type of 'foo' to be
> > foo :: forall a. IDs a => () -> a
> > If you declare foo as a value, though, you run into the dreaded
> > monomorphism restriction, and you might get a complaint from the
> > compiler about ambiguity.
> > foo2 = sameId newId 3
foo2 = startId
> > The monomorphism restriction forces values to be values; otherwise
> > consider this
> > -- the usual 'expensive' computation
> > fib :: Num a => a -> a
> > fib 0 = 1
> > fib n = fib (n-1) + fib (n-2)
> > x = fib 100000
> > What's the type of x? Most generally, it's
> > x :: Num a => a
> > But this means that x will be recalculated every time it's used; the
> > value can't be saved since x doesn't represent a single value but
> > rather a separate value for each instance of Num. You are allowed to
> > manually specify this type, but without it, the compiler says 'You
> > meant this to be a value!' and forces it to a particular type if it
> > can, or complains about ambiguity if it can't. As to how it does so,
> > look up the rules for defaulting and monomorphism in the Haskell
> > report.
> > -- ryan
More information about the Haskell-Cafe