Of course. Here is a short and idiomatic F# function that accomplishes this using Array2D.init.
This approach is concise because Array2D.init creates a 2D array by calling a generator function for each cell, providing the y (row) and x (column) indices.
/// Converts a Map with (x,y) coordinate keys to a 2D boolean array.
/// A cell at [y,x] in the array is true if the key (x,y) exists in the map.
let mapTo2DArray (map: Map<int*int, bool>) (xsize: int) (ysize: int) : bool[,] =
// Create a 2D array of size ysize x xsize.
// The generator function (fun y x -> ...) is called for each cell.
// It checks if the coordinate key (x, y) exists in the map.
Array2D.init ysize xsize (fun y x ->
Map.containsKey (x, y) map
)
// --- Example Usage ---
// 1. Define the size of our grid
let width = 5
let height = 4
// 2. Create a map with some coordinate keys.
// The boolean value associated with the key doesn't matter for this function.
let coordinates =
Map.ofList [
(0, 0), true
(2, 1), true
(3, 1), false // The value is false, but the key exists, so it will be true
(4, 3), true
(9, 9), true // This key is outside the bounds and will be ignored
]
// 3. Call the function
let grid = mapTo2DArray coordinates width height
// 4. Print the result for verification
printfn "Input Map: %A" coordinates
printfn "Output Grid (%d x %d):" width height
for y in 0 .. height - 1 do
for x in 0 .. width - 1 do
// Print 'T' for true, '.' for false
let charToPrint = if grid.[y, x] then 'T' else '.'
printf "%c " charToPrint
printfn "" // Newline after each row
(*
Expected Output:
Input Map: map [(0, 0, true); (2, 1, true); (3, 1, false); (4, 3, true); (9, 9, true)]
Output Grid (5 x 4):
T . . . .
. . T T .
. . . . .
. . . . T
*)
Key Points:
Array2D.init ysize xsize: This is the standard F# function for creating and initializing a 2D array. Note that the dimensions are provided as height (ysize) then width (xsize).
(fun y x -> ...): This is an anonymous function (lambda) that Array2D.init executes for every cell in the new array. It automatically receives the y (row index) and x (column index) for the cell it needs to populate.
Map.containsKey (x, y) map: This is the core logic. It efficiently checks if the key (x, y) exists in the input map and returns a bool, which is exactly what we need for our new array's value.
- Indexing: Remember that .NET 2D arrays are indexed by
[row, column], which corresponds to grid.[y, x], while our coordinate keys are stored as (x, y). The function correctly handles this mapping.