list - 将列表转换为 data.map 给出类型错误

标签 list haskell hashmap

我正在尝试将列表转换为 data.map,以便从如下列表中:

mylist = ["one","one","two","three","two","two","three","four","four","four","four","five","five","two"]

我得到类似的东西:

("one", 2)  ("two", 4) ...

我正在尝试以下代码:

import qualified Data.Map as Map
import Data.List 

list2dict [] mymap = print mymap
list2dict [y:ys] mymap = do
    if (Map.lookup y mymap) /= Nothing
    then list2dict [ys] $ Map.insert y ((Map.lookup y) + 1) mymap 
    else list2dict [ys] $ Map.insert y 1 mymap 

mylist = ["one","one","two","three","two","two","three","four","four","four","four","five","five","two"]
main = do
    list2dict (sort mylist) $ Map.empty

但是,我收到以下错误:

soq_list2dict.hs:5:1: error:
    • Non type-variable argument
        in the constraint: Show (Map.Map k a -> Maybe a)
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        list2dict :: forall a k.
                     (Show (Map.Map k a -> Maybe a), Show k, Ord k,
                      Num (Map.Map k a -> Maybe a), Eq (Map.Map k a -> Maybe a)) =>
                     [[k]] -> Map.Map k (Map.Map k a -> Maybe a) -> IO ()

如何解决?

编辑:使用 (y:ys) 而不是 [y:ys] 会出现以下错误:

soq_list2dict.hs:5:1: error:
    • Occurs check: cannot construct the infinite type: k ~ [k]
      Expected type: [[k]] -> Map.Map k (Map.Map k a -> Maybe a) -> IO ()
        Actual type: [k] -> Map.Map k (Map.Map k a -> Maybe a) -> IO ()
    • Relevant bindings include
        list2dict :: [[k]] -> Map.Map k (Map.Map k a -> Maybe a) -> IO ()
          (bound at soq_list2dict.hs:5:1)

最佳答案

Willem Van Onsem 已经在评论中指出了第一个问题:您使用了 [y:ys] 而不是 (y:ys)。第二个问题是您在两个地方使用了 [ys] 而不是 ys。第三个问题是你说 ((Map.lookup y) + 1),它创建了一个无意义的类型。 (即使您使用 ((Map.lookup y mymap) + 1) 代替,这更接近于正确,您仍然会得到一个不同的错误。)这种方式将起作用:

list2dict (y:ys) mymap = case Map.lookup y mymap of
    Just x -> list2dict ys $ Map.insert y (x + 1) mymap
    Nothing -> list2dict ys $ Map.insert y 1 mymap

请注意,我在 Maybe 上进行模式匹配,而不是使用 if 对其进行测试,然后尝试在之后单独提取值。

关于list - 将列表转换为 data.map 给出类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57960636/

相关文章:

haskell - 使用 ExistentialQuantification 扩展时派生显示?

java - 添加一个映射值来设置它是否与参数匹配

java.io.NotSerializableException : java. util.HashMap$值

python - python 列表的子集基于同一列表的元素组,pythonically

python - 迭代特定列表的最快方法?

java - Lombok @EqualsAndHashCode 在一个有列表的类上

java - 如何将字符串转换为 double

Python列表: Pythonic way to get unique items in given List from a given Set

haskell - 如何在 Haskell 中生成随机数列表

shell - 如何从 haskell 程序调用 bash 或 shell 脚本?