weedweaver
12-18-2004, 07:17 PM
i am writing a set module as an abstract data type implemented as an ordered list:
module Set
(
Set, -- type constructor
emptySet, -- Ord a => Set a
addElement, -- Ord a => a -> Set a -> Set a
--removeElement, -- Ord a => a -> Set a -> Set a
member, -- Ord a => a -> Set a -> Bool
union, -- Ord a => Set a -> Set a -> Set a
intersection, -- Ord a => Set a -> Set a -> Set a
--difference, -- Ord a => Set a -> Set a -> Set a
--listSet, -- Ord a => Set a -> [a]
--setList -- Ord a => [a] -> Set a
) where
newtype Set a = MkSet [a] deriving Show
emptySet :: Set a
emptySet = MkSet []
addElement :: Ord a => a -> Set a -> Set a
addElement elem (MkSet []) = MkSet [elem]
member :: Ord a => a -> Set a -> Bool
member elem (MkSet []) = False
member elem (MkSet (x:xs))
| x < elem = member elem (MkSet xs)
| x == elem = True
| otherwise = False
union :: Ord a => Set a -> Set a -> Set a
union (MkSet xs) (MkSet ys) = MkSet (uni xs ys)
uni :: Ord a => [a] -> [a] -> [a]
uni [] ys = ys
uni xs [] = xs
uni (x:xs) (y:ys)
| x < y = x : uni xs (y:ys)
| x == y = x : uni xs ys
| otherwise = y : uni (x:xs) ys
intersection :: Ord a => Set a -> Set a -> Set a
intersection (MkSet xs) (MkSet ys) = MkSet (int xs ys)
int :: Ord a => [a] -> [a] -> [a]
int [] ys = []
int xs [] = []
int (x:xs) (y:ys)
| x < y = int xs (y:ys)
| x == y = x : int xs ys
| otherwise = int (x:xs) ys
i am having problems trying to work out how add element and remove element would work. any suggestions? cheers.
module Set
(
Set, -- type constructor
emptySet, -- Ord a => Set a
addElement, -- Ord a => a -> Set a -> Set a
--removeElement, -- Ord a => a -> Set a -> Set a
member, -- Ord a => a -> Set a -> Bool
union, -- Ord a => Set a -> Set a -> Set a
intersection, -- Ord a => Set a -> Set a -> Set a
--difference, -- Ord a => Set a -> Set a -> Set a
--listSet, -- Ord a => Set a -> [a]
--setList -- Ord a => [a] -> Set a
) where
newtype Set a = MkSet [a] deriving Show
emptySet :: Set a
emptySet = MkSet []
addElement :: Ord a => a -> Set a -> Set a
addElement elem (MkSet []) = MkSet [elem]
member :: Ord a => a -> Set a -> Bool
member elem (MkSet []) = False
member elem (MkSet (x:xs))
| x < elem = member elem (MkSet xs)
| x == elem = True
| otherwise = False
union :: Ord a => Set a -> Set a -> Set a
union (MkSet xs) (MkSet ys) = MkSet (uni xs ys)
uni :: Ord a => [a] -> [a] -> [a]
uni [] ys = ys
uni xs [] = xs
uni (x:xs) (y:ys)
| x < y = x : uni xs (y:ys)
| x == y = x : uni xs ys
| otherwise = y : uni (x:xs) ys
intersection :: Ord a => Set a -> Set a -> Set a
intersection (MkSet xs) (MkSet ys) = MkSet (int xs ys)
int :: Ord a => [a] -> [a] -> [a]
int [] ys = []
int xs [] = []
int (x:xs) (y:ys)
| x < y = int xs (y:ys)
| x == y = x : int xs ys
| otherwise = int (x:xs) ys
i am having problems trying to work out how add element and remove element would work. any suggestions? cheers.