gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:55:54 24 4
gpt4 key购买 nike

提供的 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 处理“外部列表”,第二个 List.indexedMap 处理“内部列表”,其中 outerinner 分别指代这两个列表中的索引。

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

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

关于list - 如何为 Grid (2d List) 类型制作 indexedMap 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29795184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com