我想让数据类型Moneda
成为 Semigroup 的实例,并将关联操作实现为+
. 我很难正确理解它。
我找到的工作解决方案如下:
data Moneda a = RON Double | EUR Double deriving (Show)
instance Num a => Num (Moneda a) where
(RON x) + (RON y) = RON (x + y)
(RON x) + (RON y) = RON (x + y)
instance Semigroup (Moneda a) where
(<>) = (+)
Moneda
我不明白为什么下面的方法会失败,以及如何在不创建实例的情况下使其工作Num
。
data Moneda a = RON a | EUR a deriving (Show)
instance Semigroup (Moneda a) where
(<>) (RON a) (RON b) = (RON a+b) -- fails, please see error below
vs
(<>) (RON a) (RON b) = (RON a) -- works but doesn't help me because I need the a+b sum
-- cannot construct the infinite type: a ~ Moneda a
-- In the second argument of `(+)', namely `b'