[Haskell-cafe] Are casts required?

Daniel Fischer daniel.is.fischer at googlemail.com
Mon Jun 6 11:15:21 CEST 2011


On Montag, 6. Juni 2011, 09:45, Patrick Browne wrote:
> Are casts required to run the code below?
> If so why?
> Thanks,
> Pat
> 
> 
> -- Idetifiers for objects
> class (Integral i) => IDs i where
>  startId :: i
>  newId :: i -> i
>  newId i = succ i
>  sameId, notSameId :: i -> i -> Bool
> -- Assertion is not easily expressible in Haskell
> -- notSameId i newId i  = True
>  sameId i j = i == j
>  notSameId i j = not (sameId i j)
>  startId = 1
> 
> 
> instance IDs Integer where
> 
> 
> 
> -- are casts need here?
> sameId (newId startId::Integer) 3
> sameId (3::Integer) (4::Integer)
> notSameId (3::Integer) (newId (3::Integer))

The type signatures (not casts) are needed if the compiler cannot determine 
the instance to use from the context. If you have e.g. a declaration

foo :: Integer
foo = whatever

then sameId foo (newId 5) doesn't need a type signature since foo's type is 
known and determines the rest. Without such information, the compiler can't 
determine the instance it should use, so fails with an ambiguous type.
[Some module might contain

instance IDs Int where
  startId = 0
  newId k = 3*k
  sameId i j = ((i `xor` j) .&. 7) == 0

or something, then what?]



More information about the Haskell-Cafe mailing list