Haskell:对于Map中的每个(k,v),用k和v做IO()

Mic*_*ron 2 io dictionary haskell functional-programming purely-functional

我有一个Map (Int,Int) Char,我试图Char在密钥中包含的位置绘制每个s.我的职责是:

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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

mad*_*jar 5

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

(\((x,y), c) -> drawMirror c (Position x y))
Run Code Online (Sandbox Code Playgroud)

而且,mapM_(我相信你的情况来自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
Run Code Online (Sandbox Code Playgroud)

  • 您可能也喜欢[mapWithKeyM_](http://hackage.haskell.org/package/keys-3.10.1/docs/Data-Key.html#v:mapWithKeyM_). (3认同)
  • 它应该写'\((x,y),c) - > drawMirror c(位置y)` (2认同)