Semigroup和Monoid实例中约束的差异

时间:2019-06-03 14:59:00

标签: haskell category-abstractions

为什么Monoid实例不需要(Ord a,Ord b)约束,而Semigroup实例却不需要?

这是否取决于Category.Constrained类或使用GADT定义数据类型?

{-# LANGUAGE GADTs, TypeFamilies, ConstraintKinds, StandaloneDeriving #-}

module Question3 where

import Control.Category.Constrained as CC
import Data.Set as S
import Data.Map as M

data RelationMS a b where
  IdRMS :: RelationMS a a
  RMS :: (Ord a, Ord b) => Map a (Set b) -> RelationMS a b 
deriving instance (Show a, Show b) => Show (RelationMS a b)

RMS mp2 `compRMS` RMS mp1
  | M.null mp2 || M.null mp1 = RMS M.empty
  | otherwise = RMS $ M.foldrWithKey 
        (\k s acc -> M.insert k (S.foldr (\x acc2 -> case M.lookup x mp2 of
                                                    Nothing -> acc2
                                                    Just s2 -> S.union s2 acc2
                                         ) S.empty s
                                ) acc
        ) M.empty mp1

instance Category RelationMS where
    type Object RelationMS o = Ord o
    id = IdRMS
    (.) = compRMS

instance Semigroup (RelationMS a b) where 
    RMS r1 <> RMS r2 = RMS $ M.foldrWithKey (\k s acc -> M.insertWith S.union k s acc) r1  r2 

instance (Ord a, Ord b) => Monoid (RelationMS a b) where
    mempty = RMS $ M.empty
    mappend = (<>)

2 个答案:

答案 0 :(得分:8)

这当然与类别实例无关。

Semigroup实例至少在概念上确实也需要Ord,但是您已经将其打包在GADT中(在Id情况下除外,因为它不需要无关紧要),因此无需在实例头中提及约束。

对于mempty,您手边没有一个RelationMS值,您无法从中读出(Ord a, Ord b)约束。恰恰相反:您需要提供这些约束,因为您现在正在尝试包装此类GADT!这就是Monoid实例在其头部需要约束的原因,而Semigroup实例则不需要约束。

答案 1 :(得分:2)

  

为什么Monoid实例不需要(Ord a,Ord b)约束,而Semigroup实例却不需要?

尝试消除约束并让GHC告诉您原因。

ac.hs:33:14: error:
    • No instance for (Ord a) arising from a use of ‘RMS’
      Possible fix:
        add (Ord a) to the context of the instance declaration
    • In the expression: RMS $ M.empty
      In an equation for ‘mempty’: mempty = RMS $ M.empty
      In the instance declaration for ‘Monoid (RelationMS a b)’
   |
33 |     mempty = RMS $ M.empty
   |

那么RMS需要Ord a吗?你说:

  RMS :: (Ord a, Ord b) => Map a (Set b) -> RelationMS a b

所以,是的。