简体   繁体   中英

Pragma syntax in Haskell

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.

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)

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

{-# LANGUAGE  #-}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM