2

我有一个Map (Int,Int) Char,我正在尝试将其中的每个Chars 绘制在键中包含的位置。我的职能是:

import qualified Data.Map.Strict as SM
data Position = Position !GLint !GLint

drawMirrors :: SM.Map (Int,Int) Char -> IO()
drawMirrors mirrors = do
    mapM_ (\(x,y) c -> drawMirror c (Position x y)) mirrors

drawMirror :: Char -> Position -> IO()
drawMirror orientation (Position x y) = do
    -- Some irrelevant stuff

在线drawMirrors mirrors = do mapM_ (\(x,y) c -> drawMirror c (Position x y)) mirrors上,我收到错误消息:

src\Main.hs:200:33:

Couldn't match expected type `Char -> IO ()'
            with actual type `IO b0'
The lambda expression `\ (x, y) c -> drawMirror c (Position y)'
has two arguments,
but its type `(t0, GLint) -> IO b0' has only one
In the first argument of `mapM_', namely
  `(\ (x, y) c -> drawMirror c (Position y))'
In a stmt of a 'do' block:
  mapM_ (\ (x, y) c -> drawMirror c (Position y)) mirrors

如何在drawMirrors中获取字典中的所有键和值并drawMirror使用这些键和值应用函数?

4

2 回答 2

5

你的 lambda, \(x,y) c -> drawMirror c (Position x y), 有两个参数。但是,它是使用表单的单个参数调用的(key, value)(在您的情况下为((x, y), c).

(\((x,y), c) -> drawMirror c (Position x y))

此外,mapM_(我相信你的情况是 from Data.Foldable)只遍历键,所以你可能想调用SM.toList一个(key, value).

最终结果是:

drawMirrors :: SM.Map (Int,Int) Char -> IO()
drawMirrors mirrors = do
    mapM_ (\((x,y), c) -> drawMirror c (Position x y)) $ SM.toList mirrors
于 2015-02-09T11:12:07.910 回答
0

我一直在玩这个,并找到了一种使用方法来mapM_代替mapWithKeyM_. 具体来说,

{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleInstances #-}

data UnCurry :: (* -> * -> *) -> * -> * where
  UnCurry :: f k v -> UnCurry f (k, v)

instance Foldable (UnCurry Map) where
  foldr c n (UnCurry m) = M.foldrWithKey go n m
    where
      go k a b = c (k, a) b

现在,您可以使用mapM_ f (UnCurry m)对 中的每个键值对执行操作Map

于 2015-02-09T21:58:30.527 回答