无法匹配预期类型'Map k0 a'

时间:2015-10-19 17:24:00

标签: haskell

以下是我的代码:

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

我从上一个函数收到错误,错误声明是

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

我似乎无法发现错误的来源。我提到了其他用户在这里遇到类似问题的帖子,但我仍然无法理解错误‘Map k0 a’。那么,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

  

我似乎无法发现错误的来源。

xs[a],对吗?您正在尝试使用 foldr吗? Data.List一个或Data.Map一个?

我的建议是将编译器更新为7.10并使用Foldable中的折叠。