[英]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’ "
我相信这段代码应该可以工作,但不能工作,因为我使用的是 Haskell For Mac,它可能对编译指示使用不同的符号。
当您使用GeneralizedNewtypeDeriving
,您仍然需要在deriving
子句中指定要从包装类型“借用”哪些实例,因此您定义了Goat
类型:
newtype Goats = Goats Int deriving (Eq, Show, TooMany)
请注意,就像@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)
在 GHCi 中,我们可以查询,例如:
*Practice> tooMany (Goats 12)
False
虽然我在 Linux 机器上做了这个实验,但我会很惊讶这在不同的平台上不起作用。 特别是因为这些语言扩展与它们运行的平台没有太大关系。 语言扩展通常是平台无关的,因此就像@DanielWagner 所说的那样,在所有平台上都应该在deriving
添加类型类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.