If you seen this before I apologise I believe I sent it to the local
news group instead of Haskell. >:-|
Even without records you can get some oop benefits out of "Haskell"
(actually gofer and I believe hbc) using Constructor Classes.
My problem has been that I normally write my programs with the
"cheapest" possible datastructures. Typically lists since there are so
many nice prelude functions working on lists. Later when the speed
deficiencies become apparent I have to change the program to use other
data structures this is typically difficult often it is easier to
rewrite the whole program. Using constructor classes has made my life
easier because now I can write my programs so they are independente
(well less dependent at least) on the actuall implementation of my
datastructures.
Following example shows how one can define a SET constructor class
class Set s a where
meet :: s a -> s a -> s a
union :: s a -> s a -> s a
member :: a -> s a -> Bool
toSet :: [a] -> s a
fromSet :: s a -> [a]
data SimpleSet a = SimpleSet [a]
instance Eq a => Set SimpleSet a where
union (SimpleSet xs) (SimpleSet ys) = SimpleSet (nub (xs ++ ys))
meet (SimpleSet xs) (SimpleSet ys) = SimpleSet (filter (`elem` xs) ys)
x `member` (SimpleSet xs) = x `elem` xs
toSet = SimpleSet
fromSet (SimpleSet xs) = xs
data OrdSet a = OrdSet [a]
instance Ord a => Set OrdSet a where
meet (OrdSet xs) (OrdSet ys) = OrdSet (m xs ys)
where
m a@(x:xs) b@(y:ys)
| x < y = m xs b
| x == y = x : m xs ys
| x > y = m a ys
m _ _ = []
union (OrdSet xs) (OrdSet ys) = OrdSet (j xs ys)
where
j [] y = y
j x [] = x
j a@(x:xs) b@(y:ys)
| x < y = x : j xs b
| x == y = x : j xs ys
| x > y = y : j a ys
x `member` (OrdSet xs) = x `elem` xs
toSet = OrdSet . sort
fromSet (OrdSet xs) = xs
A third possibility is to use arrays if one wants quick member test
but can accept slow union and meet.
I also use a MAP constructor calls that is like array but also have
list and binary tree implementations. This is nice because often my
index type is not enum from the beginning and by using the list
implementation I only need Eq using binary trees I need Ord and using
arrays I need Enum.
At te moment I'm working to see how far one can get with this
programming style. What kind of changes one can make without changing
the program.
Enjoy
Carsten Kehler Holst