以前,为了在类型类上使用量化约束,例如Ord,您必须在实例中包含超类,如下所示:
newtype A f = A (f Int)
deriving instance (forall a. Eq a => Eq (f a)) => Eq (A f)
deriving instance (forall a. Eq a => Eq (f a), forall a. Ord a => Ord (f a)) => Ord (A f)
Run Code Online (Sandbox Code Playgroud)
(这实际上正是这个问题中给出的解决方案)。
但是,在 GHC 9 中,上述代码不起作用。它失败并出现以下错误:
• Could not deduce (Eq (f a))
from the context: (forall a. Eq a => Eq (f a),
forall a. Ord a => Ord (f a))
bound …Run Code Online (Sandbox Code Playgroud) 我有一个类似 Set 的数据结构,作为 Trie 实现,其定义如下:
import qualified Data.Map as M
import Data.Foldable (Foldable, foldr)
import Prelude hiding (foldr)
import Data.Maybe (fromMaybe)
data Trie a = Trie { endHere :: Bool
, getTrie :: M.Map a (Trie a)
} deriving (Eq)
Run Code Online (Sandbox Code Playgroud)
插入操作如下所示:
insert :: (Ord a, Foldable f) => f a -> Trie a -> Trie a
insert = foldr f (\(Trie _ m) -> Trie True m) where
f e a = overMap (M.alter (Just . a . fromMaybe (Trie …Run Code Online (Sandbox Code Playgroud) 我在 haskell 中设计了以下联合运算符:
data Set a = Set (a-> Bool)
union :: Set a -> Set a -> Set a
union (Set mem1) (Set mem2) = Set ( \x -> mem1 x || mem2 x)
instance Semigroup (Set a) where
(<>) = union
instance Monoid (Set a) where
mempty = Set ( \_ -> False) -- Empty set identity element
mappend = (<>) -- Union monoid operation
Run Code Online (Sandbox Code Playgroud)
我知道对于幺半群实例,它需要满足结合律和恒等律。使用联合运算符,它似乎确实满足了这一点。为此创建一个幺半群实例可能会出现什么问题?