如何为 Grid (2d List) 类型制作 indexedMap 函数?

How to make an indexedMap function for a Grid (2d List) type?

提供的 List 类型有一个 indexedMap 函数:( http://package.elm-lang.org/packages/elm-lang/core/2.0.0/List#indexedMap )

indexedMap : (Int -> a -> b) -> List a -> List b
Same as map but the function is also applied to the index of each element (starting at zero).

indexedMap (,) ["Tom","Sue","Bob"] == [ (0,"Tom"), (1,"Sue"), (2,"Bob") ]

我创建了一个 Grid 类型,定义为 type alias Grid a = List (List a)

我想为这个 Grid 类型创建一个类似的 indexedMap 函数,签名为 indexedMap : ((Int, Int) -> a -> b) -> Grid a -> Grid b,但我不知道该怎么做。

您必须使用 List.indexedMap 两次:

indexedMap f grid =
  List.indexedMap
    (\outer list -> List.indexedMap (\inner item -> f (outer,inner) item) list)
    grid

第一个 List.indexedMap 处理 "outer list",第二个 List.indexedMap 处理 "inner lists",其中 outerinner 指的是索引分别在这两个列表中。

如果喜欢比较无点的风格,也可以用

indexedMap f = 
  List.indexedMap
    (\outer -> List.indexedMap (\inner -> f (outer,inner)))