← All lints

palindrome_by_hand

L0583Idiomswarn

Palindrome test by hand

s[i] against s[n - 1 - i] over 0..n / 2: is_palindrome(s)

Flagged
let s: Str = read()
let n = s.len
var ok = true
for i in 0..n / 2:
    if s[i] != s[n - 1 - i]:
        ok = false
        break
print(yes(ok))
Write instead
use std.strings.{is_palindrome}

let s: Str = read()
print(yes(is_palindrome(s)))

Why

Comparing s[i] with s[n - 1 - i] for every i in 0..n / 2 is the palindrome test, written with a mirrored index and a half-length bound that are each easy to get wrong by one. is_palindrome(s) (std.strings) is that test: O(n)O(n), stops at the first mismatch, and works on any Indexed sequence, so a List<Int> or an array is tested the same way as a Str. Comparing one sequence against the mirror of another, s[i] == t[n - 1 - i], is a different question and is not reported. There is no automatic fix, because the loop usually sets a flag or breaks, and the code that reads it has to change 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 s: Str = read()
let t: Str = read()
let n = s.len
var same = 0
for i in 0..n / 2:
    if s[i] == t[n - 1 - i]:
        same += 1
print(same)

Turn it off

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

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