Sentinel value meaning absent
var memo: [D]Int = -1 tested with == -1: [D]?Int starting at None
let n: 1..=90 = read()
var memo: [0..=90]Int = -1
fn fib(i: Int) -> Int:
if i < 2:
return i
if memo[i] != -1:
return memo[i]
memo[i] = fib(i - 1) + fib(i - 2)
memo[i]
print(fib(n))let n: 1..=90 = read()
var memo: [0..=90]?Int = None
fn fib(i: Int) -> Int:
if i < 2:
return i
if let v = memo[i]:
return v
let v = fib(i - 1) + fib(i - 2)
memo[i] = v
v
print(fib(n))Why
C++ marks "not computed yet" or "unreached" with a value the answer can't take: -1 in a memo table or a BFS distance grid, 1e18 in Dijkstra. The type still says Int, so nothing stops that value being read as a real one: printed, added to (INF + c overflows), or compared with the wrong sentinel. ?Int says "maybe absent" in the type: start the table at None (var memo: [0..=90]?Int = None), test it with if let v = memo[i]: or memo[i].is_none, and read it with memo[i]! or memo[i] ?? -1 where the output wants -1. An unset entry then can't be used by mistake.
The lint fires on a var table or list filled with -1 or a value of at least 10**9 in size, when the file compares an entry with that value (or, for a large one, with < or >, as a relaxation does). It has no fix: each read needs its own choice of !, ?? or if let.
The practice it serves
A hand-written pattern the language or the standard library already says in one step. Family: O. Optionals and sentinels.
Not flagged
A near miss: close to the pattern, but not it.
let n: 1..=90 = read()
var ways: [0..=90]Int = 0
ways[0] = 1
for i in 1..=n:
ways[i] = ways[i - 1] + (if i >= 2: ways[i - 2] else: 0)
print(ways[n])Turn it off
For one block, wrap it in with lint(sentinel_table: allow):. For a project, add sentinel_table = "allow" under [lints] in cp.toml.
Generated from spec/lints/sentinel_table, the same record the linter is built from.