Pragma syntax in Haskell

Viewed 151
module Practice where

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

class TooMany a where 
  tooMany :: a -> Bool

instance TooMany Int where
   tooMany n = n > 42 

newtype Goats =
  Goats Int deriving (Eq, Show)

--What I load into the playground
tooMany (Goats 17)

--the error I get: " No instance for (TooMany Goats) arising from a use of ‘tooMany’ "

I believe that this code should work but is not working because I am using Haskell For Mac which may use different notation for pragmas.

1 Answers

When you use GeneralizedNewtypeDeriving, you still need to specify what instances you want to "borrow" from the wrapped type in the deriving clause, so you define the Goat type with:

newtype Goats = Goats Int deriving (Eq, Show, TooMany)

Note that, like @RobinZigmond says, you need to define the pragmas at the top of the file, so:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

module Practice where

class TooMany a where 
  tooMany :: a -> Bool

instance TooMany Int where
   tooMany n = n > 42 

newtype Goats = Goats Int deriving (Eq, Show, TooMany)

In GHCi, we can then query, for example:

*Practice> tooMany (Goats 12)
False

Although I did this experiment on a Linux machine, I would be very surprised that a this does not work on a different platform. Especially since such language extensions have not much to do with the platform they run on. Language extensions are usually platform-indepdent, hence like @DanielWagner says, adding the type class in the deriving should be done on all platforms.

Related