简体   繁体   English

在Haskell中使用列表数据结构创建集合数据类型

[英]Making a set data type with list data structure in Haskell

Write insert and member operations in Haskell. 在Haskell中编写插入和成员操作。 Make sure that in ML and Haskell your Set data type is distinct from a list. 确保在ML和Haskell中,您的Set数据类型与列表不同。 In Haskell, define your Set type to be an instance of classes Eq and Show. 在Haskell中,将您的Set类型定义为Eq和Show类的实例。

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

The code I written above just makes it have functions that perform on lists. 我上面编写的代码仅具有在列表上执行的功能。

Is there a way to make this into a class? 有没有办法将其纳入课堂? Sorry, I'm just learning functional programming. 抱歉,我正在学习函数式编程。 Is there a way to actually make a Set class that has member variables with such as a list? 有没有一种方法可以真正使Set类具有成员变量,例如列表?

Your data type here is [a] , which already has such instances available, including Eq and Show (that by the way do the right thing). 这里的数据类型是[a] ,它已经具有可用的实例,包括EqShow (顺便说一句正确的事)。

If you want to have write your own instances, you should newtype the underlying type, in a fashion similar to: 如果你想有写自己的情况下,你应该newtype的基本类型,在类似的方式:

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

Then you can write: 然后您可以编写:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM