Reputation: 563
hey everyone I am trying to figure out how to make a set data type in haskell, but I cannot figure this out, this is what i have so far, i am a bit confused
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)
Thanks for the help!
Upvotes: 3
Views: 7181
Reputation: 7414
From your code it seems you have already understood, that a set can be seen as a list without duplicates. So let us express this in a simple type definition:
data Set a = Set [a]
In order to ensure that there are no duplicates, one can introduce 'smart constructors' which are functions that aren't technically a constructor, but which are used as such.
empty :: Set a
empty = Set []
We'll need another one to create non-empty sets. Let's have a look at your insert
function. Why does it return a Bool
? Shouldn't it return a set? Why does insert
expect two sets? So to insert an integer into a set of integers one could you use the following type signature:
insert :: Integer -> Set Integer -> Set Integer
The implementation consists of two cases: 1. the given integer is not in the given set, and 2. the given integer is in the given set.
insert x (Set xs)
| not (x `elem` xs) = Set (x:xs)
| otherwise = Set xs
Since, this question seems to be part of a homework assignment. I'd say you should try to figure out how to implement elem
yourself.
Upvotes: 7