【问题标题】:How to make an indexedMap function for a Grid (2d List) type?如何为 Grid (2d List) 类型创建 indexedMap 函数?
【发布时间】:2015-06-29 23:17:26
【问题描述】:

对于提供的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 function dictionary elm


    【解决方案1】:

    你必须使用两次List.indexedMap

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

    第一个List.indexedMap 处理“外部列表”,第二个List.indexedMap 处理“内部列表”,其中outerinner 分别指这两个列表中的索引。

    如果你更喜欢无点风格,也可以使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      相关资源
      最近更新 更多