Alternative to multidimensional array?

Building a 2D game, and I’ve used multidimensional array’s in the past. However, the Array version in Elm is a bit unwieldy because of all the Maybe’s + nested rows. The grid is known ahead of time, and there won’t be resizing of the lists later. Is there another data type I could use?

In general I would make a Grid module and experiment with it’s internal representation.

An easy option is to just use a 1-d Array:

module Grid exposing (Grid, init, get)

import Array exposing (Array)

type Grid a =
  Grid Int Int (Array a)

init : Int -> Int -> a -> Grid a 
init w h initial =
  Array.initialize (w * h) (always initial)

get : Int -> Int -> Grid a -> Maybe a 
get x y (Grid w h arr) =
   Array.get (y * w + x) arr

This would also be a great place to add domain specific functions that will make your domain logic neater:


neighbours : Int -> Int -> Grid a -> List a 
neighbours x y (Grid w h arr as grid) =
  List.filterMap (\(x_, y_) ->
     if x_ >= 0 && x_ < w && y_ >= 0 && y_ < h then 
         get x_ y_ grid   

     else 
          Nothing
    ) [ ( x - 1, y), ( x, y - 1), (x + 1, y), (x, y + 1) ]

or what not.

Finally a quick search for “grid” on elm packages reveals a few decent looking options.

3 Likes

If your grid has <= 60 rows/columns, you might want to try the fixed size and safely accessible Chadtech/elm-vector

If you’re up for something more powerful/generic/experimental,
there’s lue-bird/elm-typesafe-array which allows you to safely access elements when it knows its array length. If you have questions on that, you can ask me here or @lue on slack.

1 Like

There is also Dict (Int,Int) Cell
Examples:
Getting neighbours is Dict.filter (x and y absolute value one off asked position)

And allowed movement for a horse in chess is x=2 off and y is one off or the other way around and not outside board limits.

1 Like

Rad, I didn’t even think to search for “Grid”, hah, appreciate that and the sample code!

Dude, this Vector is doooope!

Oh man, I completely missed that filter gives you a Dict back, I just assumed everything was a Maybe or List, appreciate this!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.