JohnQ
JohnQ

Reputation: 1093

Implementing a simple associative map in Haskell

in this period I am learning Haskell but I have problems solving a simple exercise.

I would like to write a simple associative map data structure to exercise myself.

This is the code I have written so far:

-- It represents a simple ordered couple in the form (key, value)
data Element a b = Element (a, b)
    deriving (Show)

-- It represents a (unordered) list of elements in the form (key, value)
data Dictionary a b = Dictionary [Element a b]
    deriving (Show)

-- It represents a simple dictionary which will be used for my tests
t :: Dictionary Char Int
t = Dictionary [Element ('a', 1), Element ('b', 2), Element ('a', 3)]

Now I am trying to write a simple method to return a list of couples in the form (a, b). I am doing it to exercise myself and to provide a simple function which would be useful for the other methods (find, etc.).

I have written this piece of code but I know it's wrong:

couples :: Dictionary a b -> [(a, b)]
couples (Dictionary t) = [(k , v) | (k, v) <- t]

The problem is that obviously "t" is not a list of couples: it's composed by a list of elements which are composed by a type constructor "Element" followed by an ordered couple.

How could I "get rid" of the "Element" type constructor? I have no idea...

Thank you in advance.

Upvotes: 1

Views: 1272

Answers (1)

Dirk Holsopple
Dirk Holsopple

Reputation: 8831

Just add the Element constructor in the pattern-match.

couples :: Dictionary a b -> [(a, b)]
couples (Dictionary t) = [(k , v) | (Element (k, v)) <- t]

Upvotes: 4

Related Questions