Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Created January 15, 2015 03:06
Show Gist options
  • Save JustinSDK/8d568537a3496a7bfa07 to your computer and use it in GitHub Desktop.
Save JustinSDK/8d568537a3496a7bfa07 to your computer and use it in GitHub Desktop.
〈Haskell Tutorial(19)Data.Set 與 Data.Map 模組〉題目解答之二
module Set
(
fromList,
intersection,
union
) where
import qualified Tree
data Set a = Set (Tree.Tree a)
fromList :: Ord a => [a] -> Set a
fromList = Set . Tree.fromList
intersection :: Ord a => Set a -> Set a -> Set a
intersection (Set t1) (Set t2) =
let l2 = Tree.toList t2
in Set (Tree.fromList (filter (`elem` l2) (Tree.toList t1)))
union :: Ord a => Set a -> Set a -> Set a
union (Set t1) (Set t2) =
let l = filter (\ele -> not (Tree.node ele t2)) (Tree.toList t1)
in Set (foldr (\ele t -> Tree.insert ele t) t2 l)
toList :: Set a -> [a]
toList (Set t) = Tree.toList t
instance Show a => Show (Set a) where
show set = "fromList " ++ (show . toList) set
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment