2
votes

I want to make a typeclass Size with a method that given a value computes the number of constructors in this value.

class Size a where
  size :: a -> Int

instance Size Int where
  size a = 1

instance Size Bool where
  size b = 1

instance Size (c,d) where
  size (c,d) = 1 + Size c + Size d

example4 :: (Bool,(Int,Bool))
example4 = (True,(3,False))
main :: IO ()    
main = do
  print (size example4)

It should give me the value 5 but I get the error Message Not in scope: data constructor `Size'.

I want to use Size Int or Size Bool in the Size(c,d) instance, but have no idea how.

My Problem is that I don't know how I can fix it, because I'm fairly new to Haskell.

1

1 Answers

4
votes

You made a typo:

size (c,d) = 1 + size c + size d

Note Size is thought as a data constructor since it has capital S. What you need is the function size.

Also, c and d also need to be types that are in the Size class, or size cannot be called on them

instance (Size c, Size d) => Size (c,d) where

So to complete it would be:

instance (Size c, Size d) => Size (c,d) where
  size (c,d) = 1 + size c + size d