在 Haskell 中创建具有列表数据结构的集合数据类型

Making a set data type with list data structure in Haskell

Write insert and member operations in Haskell. Make sure that in ML and Haskell your Set data type is distinct from a list. In Haskell, define your Set type to be an instance of classes Eq and Show.

let setAdd l n = if (elem l n) then l else l ++ [n]
let setMember l i = l !! i

我上面写的代码只是让它具有在列表上执行的功能。

有没有办法把它变成class?对不起,我刚学函数式编程。有没有办法实际制作一个 Set class,其中包含成员变量,例如列表?

你这里的数据类型是[a],它已经有这样的实例可用,包括EqShow(顺便做正确的事)。

如果您想编写自己的实例,您应该 newtype 底层类型,其方式类似于:

newtype Set a = Set { getSet :: [a] }

那你可以这样写:

instance Show a => Show (Set a) where
    show (Set a) = ...

instance Eq a => Eq (Set a) where
    Set a == Set b = ...