问题
给定一个数据类型,实现 Semigroup 实例。这是我被赋予实现的数据类型:
data Or a b = Fst a | Snd b deriving (Eq, Show, Num)
. 它应该像这样运行:
Prelude> Fst 1 <> Snd 2
Snd 2
Prelude> Fst 1 <> Fst 2
Fst 2
Prelude> Snd 1 <> Fst 2
Snd 1
Prelude> Snd 1 <> Snd 2
Snd 1
当我测试像> Fst "help" <> Fst "me"
它一样的值时,它可以正常工作,但是当我测试其他值时,我得到了错误。当我尝试通过从错误中派生类来修复这些错误时,我会遇到更多错误。我在这里做错了什么?
我的代码
data Or a b =
Fst a
| Snd b
deriving (Eq, Show)
instance (Semigroup a, Semigroup b, Num a, Num b) => Semigroup (Or a b) where
(Snd a) <> _ = Snd a
_ <> (Snd a) = Snd a
(Fst a) <> (Fst b) = Fst b
错误
当我尝试使用整数进行测试时,> Fst 1 <> Fst 2
我得到:
No instance for (Num a0) arising from a use of ‘it’
The type variable ‘a0’ is ambiguous
Note: there are several potential instances:
instance RealFloat a => Num (Data.Complex.Complex a)
-- Defined in ‘Data.Complex’
instance Data.Fixed.HasResolution a => Num (Data.Fixed.Fixed a)
-- Defined in ‘Data.Fixed’
instance forall (k :: BOX) (f :: k -> *) (a :: k).
Num (f a) =>
Num (Data.Monoid.Alt f a)
-- Defined in ‘Data.Monoid’
...plus 21 others
In the first argument of ‘print’, namely ‘it’
In a stmt of an interactive GHCi command: print it
当我尝试派生 Num 类时data Or a b = Fst a | Snd b deriving (Eq, Show, Num)
,我得到:
Can't make a derived instance of ‘Num (Or a b)’:
‘Num’ is not a derivable class
In the data declaration for ‘Or’
Failed, modules loaded: none.