Owen
Owen

Reputation: 43

Haskell data structures oddity

I've been attempting to write a small file to try out a bag-like data structure. So far my code is as follows:

data Fruit = Apple | Banana | Pear deriving (Eq, Show)
data Bag a = EmptyBag | Contents [(a, Integer)]

emptyBag :: Bag a
emptyBag = EmptyBag

unwrap :: [a] -> a
unwrap [x] = x

isObject theObject (obj, inte) = theObject == obj

count :: Bag a -> a -> Integer
count (Contents [xs]) theObject = snd (unwrap (filter (isObject theObject) [xs]))
count EmptyBag _ = 0

But when I try and run it I get the error Could not deduce (Eq a) from the context () arising from a use of 'isObject' at ....

Whereas when I take the count function out and call snd(unwrap(filter (isObject Banana) [(Apple,1),(Banana,2)])) it happily returns 2.

Any clues on why this is, or advice on writing this kind of data structure would be much appreciated.

Upvotes: 4

Views: 387

Answers (1)

geekosaur
geekosaur

Reputation: 61369

(==) can only be used in a context that includes Eq, but when you declared count you didn't include that context. If I'm reading correctly, that would be

count :: Eq a => Bag a -> a -> Integer

If you declare count without including the type, you can ask ghci for the inferred type; or just ask for the inferred type of snd (unwrap (filter (isObject Banana) [(Apple,1),(Banana,2)]))

Upvotes: 6

Related Questions