![](/img/trans.png)
[英]Haskell - No instance for (Num (Integer -> Integer)) for function with custom data type
[英]Haskell custom data type, instance Num, and redundancy
我正在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
-- ...
只要记住,如果有人尝试将公斤加到磅中,除非您也处理这种情况,否则您的代码将出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.