如何编写半群实例?

Jon*_*eal 3 haskell functional-programming monoids

问题

给定数据类型,实现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
Run Code Online (Sandbox Code Playgroud)

当我测试像> 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  
Run Code Online (Sandbox Code Playgroud)

错误

当我尝试用整数测试时,> 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
Run Code Online (Sandbox Code Playgroud)

当我尝试推导出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.
Run Code Online (Sandbox Code Playgroud)

dfe*_*uer 5

真正的问题是你对你的实例施加的约束,你不需要它.写吧

instance Semigroup (Or a b) where
  (Snd a) <> _ = Snd a
  _ <> (Snd a) = Snd a
  (Fst a) <> (Fst b) = Fst b
Run Code Online (Sandbox Code Playgroud)

正如chepner所示,您实际上可以减少行数和模式数量,并返回其中一个参数作为结果,而不是构建它的新副本.这对效率有潜在的好处.

不太重要的是,模式中的括号都是冗余的,因为应用程序具有比任何运算符更高的优先级.