How to make indexedMap function for Grid (2d List) type?
There is a function indexedMap
for the provided type here List
: ( 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") ]
I created a type Grid
with a definitiontype alias Grid a = List (List a)
I want to create a similar function indexedMap
for this type Grid
with a signature indexedMap : ((Int, Int) -> a -> b) -> Grid a -> Grid b
, but I have no doubt how to do it.
source to share
You must use List.indexedMap
twice:
indexedMap f grid =
List.indexedMap
(\outer list -> List.indexedMap (\inner item -> f (outer,inner) item) list)
grid
The first List.indexedMap
handles the "outer list" and the second List.indexedMap
"inner lists", where outer
they inner
refer to the indices in the two lists, respectively.
If you prefer a quieter style, you can also use
indexedMap f =
List.indexedMap
(\outer -> List.indexedMap (\inner -> f (outer,inner)))
source to share