Haskell 自定义数据类型、实例数和冗余

标签 haskell types instance

我正在 Haskell 中开发一小组举重实用程序作为学习练习。我定义了一个数据类型 Weight,这样:

data Weight = Wt Float Unit 
              deriving (Show, Eq)

data Unit   = Lb | Kg 
              deriving (Show, Eq)

instance Num Weight where
  Wt x Lb + Wt y Lb = Wt (x + y) Lb
  Wt x Lb * Wt y Lb = Wt (x * y) Lb
  negate (Wt x Lb)  = Wt (negate x) Lb
  abs    (Wt x Lb)  = Wt (abs x) Lb
  signum (Wt x Lb)  = Wt (signum x) Lb
  fromInteger x     = Wt (fromInteger x) Lb
  -- Repeat for Kg...

有没有办法在 Num 实例定义中为 Unit 指定泛型类型?最好指定如下内容:

instance Num Weight where
  Wt x a + Wt y a = Wt (x + y) a
  -- ...

而不是用其他构造函数重复所有内容。

最佳答案

你可以使用守卫。下面的代码是一个错误,我相信您已经注意到了:

instance Num Weight where
    Wt x a + Wt y a = Wt (x + y) a
    -- ...

但这很好:

instance Num Weight where
    Wt x a + Wt y b | a == b = Wt (x + y) a
    -- ...

请记住,如果有人尝试将千克与磅相加,您的代码将会出错,除非您也处理这种情况。

关于Haskell 自定义数据类型、实例数和冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28666435/

相关文章:

python - 打印类实例列表的随机实例但得到 RecursionError python3

linux - 我尝试通过公共(public) ec2 实例连接私有(private) ec2 实例时如何修复错误?

haskell - 在 Haskell 中设置精度

haskell - 确认惰性评估

swift - 在 Swift 中创建绑定(bind)到特定范围的类型

python - 如何使用 isinstance 测试所有可能的整数类型

python - 使用 Python `isinstance` 是否正确?

Haskell - zip 替代方案

haskell - 是否可以在 GADT 定义中使用类型别名?

c++ - 有没有办法为非整数创建枚举数据类型?