Need to make a 2D array

This seems like it should work but it won’t compile. Is there a way to get a 2D array in ReScript?

type lightState =
  | Off
  | On

let make2DMatrix = (dimX, dimY) => {
  let matrix = Belt.Array.make(dimY, [])
  for i in 0 to dimX - 1 {
    matrix[i] = Belt.Array.make(dimY, Off) // getting error: This has type: bool; somewhere wanted: unit
  }
  matrix
}

We can create an array of length dimY and then map over it to create an array of length dimX with values as Off

Playground Link

type lightState =
  | Off
  | On

let make2DMatrix = (dimX, dimY) => {
  Belt.Array.make(dimY, ())->Belt.Array.map(() => Belt.Array.make(dimX, Off))
}

I can’t reproduce this error. Your code compiles successfully on the playground. (Link)

Edit: Do you have open Belt in your code? Belt will override the a[i] = x behavior to return true if i was in a valid range and false if it was not. If you don’t need that value, then you can use the ignore function to discard it.

+ open Belt
+ 
type lightState =
  | Off
  | On

let make2DMatrix = (dimX, dimY) => {
  let matrix = Belt.Array.make(dimY, [])
  for i in 0 to dimX - 1 {
--    matrix[i] = Belt.Array.make(dimY, Off)
++    ignore(matrix[i] = Belt.Array.make(dimY, Off))
  }
  matrix
}

A couple things to keep in mind:

  • The a[i] syntax is just sugar for the Array.get and Array.set functions. If you have your own Array module, or have Belt’s Array in scope by opening Belt, then it will override those functions and change the behavior.
  • Any time you execute a side effect and get a value that you don’t need, you can use ignore to discard it.
1 Like

For extra credit, a more efficient way of initializing a 2D array would be to use Belt.Array.makeBy, which accepts a function to create each item. This eliminates the need to loop over the array again and set each item.

type lightState = Off | On

let make2DMatrix = (x, y) => Belt.Array.makeBy(y, _ => Belt.Array.make(x, Off))
3 Likes

@johnj That was it–I had “open Belt” as a flag in my .bsconfig.json. What do you know, that info about the a[i] syntax is in the Belt docs introduction. I guess it’s been so long since I read it I forgot that was in there. :blush:

+1 for the “extra credit” solution :sunglasses: