← All lints

dx_dy_arrays

L0539Idiomswarn

Grid directions as dx/dy lists

dx = [1, -1, 0, 0]: for d in Dir4.all() with (r, c).step(d)

Flagged
let (h, w): (1..=1000, 1..=1000) = read()
let (x, y): (0..h, 0..w) = read()
let dx = [1, -1, 0, 0]
let dy = [0, 0, 1, -1]
for d in 0..4:
    print(x + dx[d], y + dy[d])
Write instead
let (h, w): (1..=1000, 1..=1000) = read()
domain R = 0..h
domain C = 0..w
let (x, y): (R, C) = read()
for d in Dir4.all():
    if let (nx, ny) = (x, y).step(d):
        print(nx, ny)

Why

int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1}; is how C++ walks a grid's neighbours: two lists that must be kept in the same order, read as x + dx[d] and y + dy[d], and then a bounds test for each step. In CP Lang a direction is a value: Dir4.all() from std.grid gives up, right, down, left (Dir8.all() adds the diagonals), and (r, c).step(d) on a grid over two domains is the neighbour cell or None when the step leaves the grid. for (nr, nc) in (r, c).adj4 is the same loop with the Nones skipped. The lint fires on two adjacent lists of 4 or 8 offsets in -1..=1. It has no fix, since the cell type and the loop change together.

The practice it serves

A hand-written pattern the language or the standard library already says in one step. Family: S.containers: deques, lists, grids, randomness.

Not flagged

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

Near miss
let n: 1..=100 = read()
let coins = [1, 5, 10, 25]
let signs = [1, -1, 1]
let dy = [0, 1, 0]
print(coins[0] + signs[0] + dy[0] + n)

Turn it off

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

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