嘿大家我试图弄清楚如何在haskell中设置数据类型,但我无法弄明白,这是我到目前为止,我有点困惑
data Set a = Node a | List {
list :: [a]
}deriving(Eq,Show,Ord)
insert :: Set Integer -> Set Integer -> Bool
insert (Node itemToInsert) (List list)
|contains (List list) (Node itemToInsert) == False = List(list:(Node itemToInsert))
contains :: Set Integer -> Set Integer -> Bool
contains (List []) (Node numberToFind) = False
contains (List (x:xs)) (Node numberToFind)
|x == (Node numberToFind) = True
|otherwise = contains (List (xs)) (Node numberToFind)
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助!
从您的代码中可以看出,您已经理解了一个集合可以被视为没有重复的列表.所以让我们用一个简单的类型定义来表达它:
data Set a = Set [a]
Run Code Online (Sandbox Code Playgroud)
为了确保不存在重复,可以引入"智能构造函数",这些函数在技术上不是构造函数,而是用作这样的函数.
empty :: Set a
empty = Set []
Run Code Online (Sandbox Code Playgroud)
我们需要另一个来创建非空集.我们来看看你的insert功能吧.它为什么会返回Bool?它不应该返回一套?为什么insert期待两套?因此,要将整数插入到一组整数中,可以使用以下类型签名:
insert :: Integer -> Set Integer -> Set Integer
Run Code Online (Sandbox Code Playgroud)
实现包括两种情况:1.给定的整数不在给定的集合中,2.给定的整数在给定的集合中.
insert x (Set xs)
| not (x `elem` xs) = Set (x:xs)
| otherwise = Set xs
Run Code Online (Sandbox Code Playgroud)
因为,这个问题似乎是家庭作业的一部分.我会说你应该试着弄清楚如何实现elem自己.