I can't seem to figure out type variables mixed with classes.

Posted by onmach on Stack Overflow See other posts from Stack Overflow or by onmach
Published on 2011-01-11T00:39:48Z Indexed on 2011/01/11 4:53 UTC
Read the original article Hit count: 149

Filed under:

I pretty much understand 3/4 the rest of the language, but every time I dip my feet into using classes in a meaningful way in my code I get permantently entrenched.

Why doesn't this extremely simple code work?

data Room n = Room n n deriving Show

class HasArea a where
  width :: (Num n) => a -> n

instance (Num n) => HasArea (Room n) where
  width (Room w h) = w

So, room width is denoted by ints or maybe floats, I don't want to restrict it at this point. Both the class and the instance restrict the n type to Nums, but it still doesn't like it and I get this error:

Couldn't match expected type `n1' against inferred type `n'
  `n1' is a rigid type variable bound by
       the type signature for `width' at Dungeon.hs:11:16
  `n' is a rigid type variable bound by
      the instance declaration at Dungeon.hs:13:14
In the expression: w
In the definition of `width': width (Room w h) = w
In the instance declaration for `HasArea (Room n)'

So it tells me the types doesn't match, but it doesn't tell me what types it thinks they are, which would be really helpful. As a side note, is there any easy way to debug an error like this? The only way I know to do it is to randomly change stuff until it works.

© Stack Overflow or respective owner

Related posts about haskell