【问题标题】:Haskell Couldn't match type `[]' with `IO'Haskell 无法将类型“[]”与“IO”匹配
【发布时间】:2014-12-14 17:49:55
【问题描述】:

我正在尝试将绘图函数映射到列表中的每个元素。函数本身 drawMap 似乎没问题,但是当我使用它时出现以下错误:

Couldn't match type `[]' with `IO'
Expected type: IO (IO Bool)
  Actual type: [IO Bool]
In the return type of a call of `drawMap'
In a stmt of a 'do' block: drawMap testMap 32 img screen
In the second argument of `($)', namely
  `do { screen <- SDL.setVideoMode 640 480 32 [SDL.SWSurface];
        img <- SDL.loadBMP "grass.bmp";
        drawMap testMap 32 img screen;
        SDL.flip screen;
        .... }'

通过阅读this,我现在了解到它与函数返回的内容有关,但我目前不知道如何修复它。

我的代码如下所示:

testMap = [Tile 0 0 1, Tile 0 1 1, Tile 0 2 1, Tile 0 3 1]

drawTile :: Int -> SDL.Surface -> SDL.Surface -> Tile -> IO Bool
drawTile tilesize img dst tile = applySurface (tileX tile * tilesize) (tileY tile * tilesize) img dst

drawMap :: [Tile] -> Int -> SDL.Surface -> SDL.Surface -> [IO Bool]
drawMap tiles tilesize img dst =
  map (drawTile tilesize img dst) tiles

main :: IO ()
main = SDL.withInit [SDL.InitEverything] $ do

  screen <- SDL.setVideoMode 640 480 32 [SDL.SWSurface]

  img <- SDL.loadBMP "grass.bmp"

  --drawTile 32 img screen (testMap !! 1)
  drawMap testMap 32 img screen

  SDL.flip screen

  mainLoop

【问题讨论】:

    标签: haskell map


    【解决方案1】:

    我想你想要:

    drawMap tiles tilesize img dst =
      mapM (drawTile tilesize img dst) tiles
    

    mapM 来自Control.MonaddrawMap 的类型变为:

    drawMap :: [Tile] -> Int -> SDL.Surface -> SDL.Surface -> IO [Bool]
    

    即它是返回 Bool 列表的 IO 操作,而不是 IO 操作列表。

    【讨论】:

    • 非常感谢@user5402。 mapM 解决了这个问题。
    猜你喜欢
    • 2021-03-24
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    相关资源
    最近更新 更多