skg22
skg22

Reputation: 37

Couldn't match expected type ‘Map k0 a’

Below is my code:

module Data.Bag where

import Data.Map hiding (map)
import Prelude hiding (foldr)

-- | Type of bags
newtype Bag a = Bag {fm :: Map a Int} deriving Eq

-- | Empty bag
emptyBag :: Bag a
emptyBag = Bag empty

-- | Add an element to a bag.
bagInsert :: Ord a => Bag a -> a -> Bag a
bagInsert Bag{ fm=bag } a
  = Bag (insertWith (+) a 1 bag)

-- | Put all elements from a list into a bag.
listToBag :: Ord a => [a] -> Bag a
listToBag xs 
   = foldr (\x bag -> bagInsert bag x) emptyBag xs

I'm getting an error from the last function and the error statement is

Couldn't match expected type ‘Map k0 a’ with actual type ‘[a]’
Relevant bindings include
  xs :: [a]
    (bound at /Users/.../Bags.hsproj/Bags.hs:20:11)
  listToBag :: [a] -> Bag a
    (bound at /Users/.../Bags.hsproj/Bags.hs:20:1)
In the third argument of ‘foldr’, namely ‘xs’
In the expression: foldr (\ x bag -> bagInsert bag x) emptyBag xs

I cannot seem to spot the source of the error. I referred to other posts made by users here that encountered similar issues but still, I am unable to understand the error ‘Map k0 a’. So, how do I go around this?

Upvotes: 2

Views: 389

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39390

I cannot seem to spot the source of the error.

xs is [a], right? And which foldr are you trying to use? The Data.List one or Data.Map one?


My suggestion would be to update the compiler to 7.10 and use folds from Foldable.

Upvotes: 5

Related Questions