Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

There's an indexedMap function for the provided List type: ( 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 made a Grid type with a definition of type alias Grid a = List (List a)

I want to make a similar indexedMap function for this Grid type with a signature of indexedMap : ((Int, Int) -> a -> b) -> Grid a -> Grid b, but I'm note sure how to do it.


1 Answers

You have to 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 the "inner lists", where outer and inner refer to the indices within those two lists, respectively.

If you prefer a more point-free style, you can also use

indexedMap f = 
  List.indexedMap
    (\outer -> List.indexedMap (\inner -> f (outer,inner)))
like image 199
Martin Huschenbett Avatar answered Feb 01 '26 17:02

Martin Huschenbett