Search code examples
haskelltypeclassnewtype

Add type variable to newtype definition


In an exercise from Haskell Programming from First Principles it says to declare an instance of TooMany for the type (Num a, TooMany a) => (a, a) by creating a newtype for it first. My problem is adding a typeclass constraint to Baz. Is it even possible? I cannot find any other examples online.

class TooMany a where
  tooMany :: a -> Bool

newtype Baz = Baz (a, a) deriving (Eq, Show)

instance TooMany Baz where
  tooMany (Baz (n, _)) = n > 42

Solution

  • You likely need to use an argument to Baz:

    newtype Baz a = Baz (a, a) deriving (Eq, Show)
            -- ^^^ --
    
    instance (Num a, TooMany a) => TooMany (Baz a) where
       ...
    

    I'm unsure about what the Num a is for, but I added that since you mentioned it.