← All lints

nested_list_grid

L0532Idiomswarn

List of lists for a fixed grid

[[0 for _ in 0..m] for _ in 0..n]: [n, m]Int = 0

Flagged
let (n, m): (1..=1000, 1..=1000) = read()
var g: List<List<Int>> = [[0 for _ in 0..m] for _ in 0..n]
g[n - 1][m - 1] = 7
print(g[n - 1][m - 1])
Write instead
let (n, m): (1..=1000, 1..=1000) = read()
var g: [n, m]Int = 0
g[n - 1, m - 1] = 7
print(g[n - 1, m - 1])

Why

vector<vector<int>> g(n, vector<int>(m)) is how C++ makes a grid, and [[0 for _ in 0..m] for _ in 0..n] is its literal translation: n separate lists, each with its own length, so nothing says the rows are all m long and every g[i][j] is checked twice. CP Lang's array type says the shape: var g: [n, m]Int = 0 is one block over the domain n by m, read and written as g[i, j], and an index the loop bounds prove needs no check at all. Rows that really differ in length (a triangle, an adjacency list) stay a List<List<T>>. The lint fires on a comprehension of a comprehension over two ranges whose cell does not depend on the loop variables. It has no fix, since each g[i][j] becomes g[i, j].

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: H. C++ habits.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
let n: 1..=1000 = read()
var tri: List<List<Int>> = [[0 for _ in 0..=i] for i in 0..n]
tri[n - 1][0] = 7
print(tri[n - 1][0])

Turn it off

For one block, wrap it in with lint(nested_list_grid: allow):. For a project, add nested_list_grid = "allow" under [lints] in cp.toml.

Generated from spec/lints/nested_list_grid, the same record the linter is built from.