我想了解Collection类型的以下两个定义之间的区别.
具有多参数类型类和功能依赖性(取自此处);
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FunctionalDependencies #-} class Eq e => Collection c e | c -> e where insert :: c -> e -> c member :: c -> e -> Bool instance Eq a => Collection [a] a where insert = flip (:) member = flip elem
只有一个类型参数;
class Collection c where insert :: Eq e => c e -> e -> c e member :: Eq e => c e -> e -> Bool instance Collection [] where insert = flip (:) member = flip elem
两者似乎编译和工作正常.两者之间是否有任何实际差异,或任何理由支持一种方法而不是另一种方法?
Fundep版本仍然有效的简单示例,但不是单参数版本,是一个Set
容器:
import qualified Data.Set as Set instance (Ord e) => Collection (Set.Set e) e where insert = Set.insert member = flip Set.member
另一个类的实例不起作用,因为您需要一个Ord
约束.现在,您可以将定义更改为
class Collection c where insert :: Ord e => c e -> e -> c e member :: Ord e => c e -> e -> Bool
但是对于像列表这样只会令人讨厌的简单容器,您还希望在那里存储非ord类型.对于Hashmaps,您还需要另一个约束.任何集合都需要这些全局和必需品.