問題
データ型を指定して、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.