Implements 2D array using nested Arrays. Useful for implementing data grids, as it specifically provides row and column operations.
Cells are accessed by row, then column. Otherwise, it works very similarly to the Array class. The documentation examples usually omit converting Lists to Arrays for brevity.
Array2D's can be constructed from an Array or List of rows, where each row is an Array or List of cells.
Array2D.fromList
[ ["Row 1-Col 1", "Row 1-Col 2"]
, ["Row 2-Col 1", "Row 2-Col 2"]
]If the nested arrays happen to be jagged, all rows will be truncated to the length of the smallest row! Be careful!
Array2D.fromList
[ [0, 1]
, [0, 1, 2]
]
-- Becomes:
[ [0, 1]
, [0, 1]
]Most examples of nested Elm components use Lists of elements with a unique, constant ID. This allows messages to always be routed to the correct sub-component, even if components are removed or added. If you use the index of the sub-component instead and the sub-component triggers a Task that takes time to complete during which the Array is modified, the completion message may be routed to the wrong sub-component.
This is hypothetical though. If your sub-components don't trigger long tasks or you don't allow rows or columns to be manipulated until the task returns, you should be fine. I think!
Create an empty Array2D
Create an Array2D from an Array of Arrays. All rows will be truncated to the length of the shortest row.
let
row1 = Array.fromList [1, 2]
row2 = Array.fromList [2, 3]
in
fromArray (Array.fromList [row1, row2])Create an Array2D from a List of Lists.
fromList [[1, 2, 3], [4, 5, 6]]Create a 2D of a given size, filled with a default element. Similar to Array.repeat
repeat 2 3 0 == [[0, 0, 0], [0, 0, 0]]Get the number of rows in an Array2D
rows [[1, 2, 3], [4, 5, 6]] == 2Get the number of columns in an Array2D
columns [[1, 2, 3], [4, 5, 6]] == 3Check if an Array2D is empty.
isEmpty [] == TrueGet a cell.
get 1 1 [[1, 2], [3, 4]] == Just 4Update a cell, returning the changed Array2D.
set 0 0 -100 [[1, 2], [3, 4]] == [[-100, 2], [3, 4]]Get an individual row
getRow 1 [[1, 2], [3, 4]] == Just [3, 4]Append a row. If the row is too long, it will be truncated, too short and it will be expanded with filler elements.
appendRow [3, 4] [[1, 2]] == [[1, 2], [3, 4]]Delete a row
get column-th cell of each row as an Array
getColumn 1 [[1, 2], [3, 4]] == [Just 2, Just 4]Append a column. Filler will be used if the column length is less than the number of rows in the Array2D. If it is longer, it will be truncated.
appendColumn [2, 2] [[1], [1]] == [[1, 2], [1,2]]Delete a column. If the index is invalid, nothing will happen.
2D version of Array.map.
map (\cell -> toString cell) [[1, 2], [3, 4]] == [["1", "2"], ["3", "4"]]2D version of Array.indexedMap. First two arguments of map function are the row and column.
indexedMap (\row column cell -> toString row) [[1, 2], [3, 4]] == [["0", "0"], ["1", "1"]]
Base Array2D type