[Haskell-cafe] Newbie Q: Overloading and type classes

Dmitri O.Kondratiev dokondr at gmail.com
Sat Jun 7 19:07:19 EDT 2008


{--
Thanks!
Yes, you got it right - I "want to make explicit the fact that the type s
depends on k and v.
So I followed your advice and used the most simple way to do what I need:
--}

class Store s where
    put :: Eq k => (k, v) -> s k v -> s k v
    get :: Eq k => k -> s k v -> Maybe v

instance Store OneCell where
    put (k1, v1) (Cell(k, v)) = Cell(k1, v1)
    get k (Cell (_, v)) = Just v

instance Store CellList where
    put (k,v) (CLst xs) = CLst ((k,v) : xs)
    get k (CLst xs) = lookup k xs


storePut :: (Store s, Eq k)  => s k v -> k -> v -> s k v
storePut store key value = put (key, value) store

storeGet :: (Store s, Eq k) => k -> s k v -> Maybe v
storeGet key store = get key store

aCell :: OneCell String Int
aCell = Cell("one", 1)
lst :: CellList Int String
lst = CLst [(1, "one"),(2, "two"),(3, "three")]

st1 = storePut aCell "two" 2
st2 = storePut lst 4 "four"

-- v1 = storeGet "one" st2 -- error
v2 = storeGet "one" st1 -- ok

{--
And what does the word "newbie" imply to you when answering my question?
In what case using 'fundeps' and 'associated types' will make sence for this
example?
--}

Thanks again for your great help!
Dima

On Sat, Jun 7, 2008 at 11:11 PM, Luke Palmer <lrpalmer at gmail.com> wrote:

>
> Oops.  Should be:
>
>    get :: k -> s k v -> Maybe v
>
> And correspondingly for the later examples.  After actually using my
> brain thinking about your problem, and reading the word "Newbie", I
> would absolutely stay away from the fundeps/associated types business.
>  :-)  Try to get this working with Cell and CellList first :-)
>
> Luke
>

> > If instead you have cell types which are restricted in what they can
> > store in different ways, you might explore fundeps or associated
> > types:
> >
> > -- fundeps
> > class Store s k v | s -> k v where
> >    put :: (k,v) -> s -> s
> >    get :: s -> Maybe v
> >
> > -- associated types
> > class Store s where
> >    type Key s :: *
> >    type Value s :: *
> >    put :: (Key s, Value s) -> s -> s
> >    get :: s -> Maybe (Value s)
> >
> > But if you can get away with the former, I would recommend that before
> > looking into these advanced extensions.
> >
> > Luke
> >
>



-- 
Dmitri O. Kondratiev
dokondr at gmail.com
http://www.geocities.com/dkondr
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20080608/4215be5d/attachment.htm


More information about the Haskell-Cafe mailing list