Lea*_*ick 1 syntax haskell pragma
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’ "
Run Code Online (Sandbox Code Playgroud)
我相信这段代码应该可以工作,但不能工作,因为我使用的是 Haskell For Mac,它可能对编译指示使用不同的符号。
当您使用 时GeneralizedNewtypeDeriving,您仍然需要在deriving子句中指定要从包装类型“借用”哪些实例,因此您可以Goat使用以下内容定义类型:
newtype Goats = Goats Int deriving (Eq, Show, TooMany)Run Code Online (Sandbox Code Playgroud)
请注意,就像@RobinZigmond 所说的,您需要在文件顶部定义编译指示,因此:
{-# 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)Run Code Online (Sandbox Code Playgroud)
在 GHCi 中,我们可以查询,例如:
*Practice> tooMany (Goats 12)
False
Run Code Online (Sandbox Code Playgroud)
虽然我在 Linux 机器上做了这个实验,但我会很惊讶这在不同的平台上不起作用。特别是因为这些语言扩展与它们运行的平台没有太大关系。语言扩展通常与平台无关,因此就像@DanielWagner 所说的那样,deriving应该在所有平台上添加类型类。