← All lints

memo_by_hand

L0554Idiomswarn

Memo table kept by hand

if k in memo: return memo[k]: @memo(map) on the fn

Flagged
let (n, k): (1..=60, 1..=60) = read()
var memo: Map<(Int, Int), Int> = Map()
fn ways(i: Int, left: Int) -> Int:
    if (i, left) in memo:
        return memo[(i, left)]
    var r = 0
    if i == n:
        r = if left == 0: 1 else: 0
    else:
        r = ways(i + 1, left)
        if left > 0:
            r += ways(i + 1, left - 1)
    memo[(i, left)] = r
    return r
print(ways(0, k))
Write instead
let (n, k): (1..=60, 1..=60) = read()
@memo(map) fn ways(i: Int, left: Int) -> Int:
    if i == n:
        return if left == 0: 1 else: 0
    var r = ways(i + 1, left)
    if left > 0:
        r += ways(i + 1, left - 1)
    return r
print(ways(0, k))

Why

A map declared beside a recursive fn, read with if key in memo: return memo[key] at the top and written before each return, is memoization by hand: three places that must agree on the key. @memo(map) on the fn says it once, and @memo(array) stores a dense table when every parameter has a bounded type (a domain, a range, Bool). The finding is on the map's declaration. There is no automatic fix, because every store has to be removed with it.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

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

Near miss
let (n, k): (1..=60, 1..=60) = read()
var memo: Map<(Int, Int), Int> = Map()
fn ways(i: Int, left: Int) -> Int:
    if (i, left) in memo:
        return 0
    memo[(i, left)] = 1
    return if i == n: 1 else: ways(i + 1, left)
print(ways(0, k))

Turn it off

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

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