gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:03:43 26 4
gpt4 key购买 nike

我正在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com