【问题标题】:How to add typeclass constraints to a newtype expression?如何将类型类约束添加到新类型表达式?
【发布时间】:2018-10-12 21:49:10
【问题描述】:

我正在阅读Haskell Programming from First Principles一书,newtype 章节中有一个练习,要求我为(Num a, TooMany a) => (a, a) 创建一个TooMany 实例。

之前的练习已经为IntGoats Int(Int, String)(Int, Int) 创建了TooMany 实例。我已经完成了这些,但不是为(Num a, TooMany a) => (a, a)

所有代码如下:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}

class TooMany a where
  tooMany :: a -> Bool

instance TooMany Int where
  tooMany n = n > 42

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

-- the following needs FlexibleInstances pragma
instance TooMany (Int, String) where
  tooMany (n, _) = n > 33

-- or do this:
newtype AnotherTooMany = AnotherTooMany (Int, String) deriving (Eq, Show, TooMany)

instance TooMany (Int, Int) where
  tooMany (n, m) = (n + m) > 44


-- THE FOLLOWING ONES ARE NOT CORRECT !!!

instance TooMany (Num a, TooMany a) => (a, a) where
  tooMany (t1, t2) = (t1 + t2) > 44

newtype YetAnotherTooMany =
  YetAnotherTooMany (Num a, TooMany a) => (a, a)
  deriving (Eq, Show, TooMany)

我应该如何更改最后两个表达式以使其正常工作?

我也参考了以下问题,但还是没有找到答案:

Adding class constraints to typeclass instance

Can a typeclass constraint be used in a newtype definition?

【问题讨论】:

  • instance (Num a, TooMany a) => TooMany (a, a)?

标签: haskell typeclass newtype


【解决方案1】:

最小的变化是这样的:

instance (Num a, Ord a, TooMany a) => TooMany (a, a) where
    tooMany (t1, t2) = (t1 + t2) > 44

关于此实例的两个注意事项:我必须添加一个 Ord 约束,因为调用了 (>),而 TooMany 约束是多余的,因为实现不会调用 tooManya 为一个论点。我怀疑预期的练习解决方案对tooMany 方法的实现略有不同——我鼓励您尝试找到一种使用TooMany a 约束而不使用Ord a 约束的方法来实现它!

对于您的newtype,正确的语法是这样的:

newtype YetAnotherTooMany a = YetAnotherTooMany (a, a)
    deriving (Eq, Show, TooMany)

您需要删除TooMany(Int, Int) 实例才能使这种确切的语法起作用,否则在派生过程中会有重叠的实例可供选择。但是,我希望预期的练习解决方案是在 (a, a) 实例根本不存在的假设下自己为此 newtype 编写实例——因为大概目标是学习如何使用 newtype 来避免首先是重叠的实例问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-06
    • 2021-05-20
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多