Credence.Pattern.PreferPatternMatchOverConditionalInRecursiveCount (credence v0.8.0)

Copy Markdown

Readability rule: Detects recursive function clauses that use an if/else to conditionally count matches, when the same logic is more idiomatically expressed via multiple pattern-matching function clauses with a guard.

The rewrite uses when head == target (not pattern-match ===) to preserve the original == semantics, which matter for int/float value equality.

Bad

def count_until([head | tail], target, stop) do
  count = if head == target, do: 1, else: 0
  count + count_until(tail, target, stop)
end

Good

def count_until([head | tail], target, stop) when head == target,
  do: 1 + count_until(tail, target, stop)

def count_until([_ | tail], target, stop),
  do: count_until(tail, target, stop)