Doing exercises from "Haskell tutorial" ...

Dmitry Astapov adept@umc.com.ua
02 Oct 2001 15:16:27 +0300


It seems like an appropriate page for aske newbie questions, isnt it?

I was reading through Haskell tutroial
(http://www.di.uminho.pt/afp98/PAPERS/Tutorial.ps) and trying to do
exercises from there. I'm stuck in the first exercise for "Classes" chapter
(page 11). I need to define SetsAsLists as an instance of Set by supplying
definitions for all Set methods, but definitions I wrote led me to adding
additional constraints on "union" and "memeber" methods. Is it ok or it's
possible to define "union" and "member" without using "==" ?

Code follows:

class Set s where
            empty :: s a
            isEmpty :: s a -> Bool
            singleton :: a -> s a
            union :: Eq a => s a -> s a -> s a
            member :: Eq a => a -> s a -> Bool
            choice :: s a -> (a, s a)

data SetsAsLists a = SL [a]

instance Set SetsAsLists where
    empty = SL []
    isEmpty (SL []) = True
    isEmpty _ = False
    singleton x = SL [x]
    member x (SL ys)  | isEmpty (SL ys)    = False
                      | otherwise          = if x==head ys
                                             then True 
                                             else member x (SL (tail ys))
    union (SL []) (SL ys) = SL ys
    union (SL (x:xs)) (SL ys) | member x (SL ys) = union (SL xs) (SL (x:ys))
                              | otherwise        = union (SL xs) (SL ys)


-- 
Dmitry Astapov //ADEpt                               E-mail: adept@umc.com.ua
GPG KeyID/fprint: F5D7639D/CA36 E6C4 815D 434D 0498  2B08 7867 4860 F5D7 639D