leanprover / leanprover/lean4

Some functions using `List.foldr` are specialized for common argument types before the tail-recursive `foldr` is available

Open
#7,750 1 comment 2 reactions 1 assignee View on GitHub

@zwarich is already working on this.

Since Apr 1, 2025.

bug P-medium
Dominant language
Lean
Stars
9.2k
Forks
990
Avg merge
1d 17h
Merged PRs (30d)
175

Description

Prerequisites

Please put an X between the brackets as you perform the following steps:

Description
#eval (List.range 1000000).sum

crashes due to a stack overflow even though List.sum is implemented via List.foldr and a csimp lemma is available for that.

The reason for this is that we define Nat.sum in List/Basic.lean, which creates the specialization of List.foldr for adding natural numbers, and it uses the naive implementation of foldr as the csimp lemma for List.foldr is not available yet. When using List.sum on a list of natural numbers later, Lean will reuse this specialization, even though the csimp lemma is available now.

Similarly, the specialization for adding lists of integers is created when defining Lean.Omega.IntList.sum, and the csimp lemma is not imported there either.

This means that in practice, users using List.sum to sum up lists of natural numbers or integers in their downstream projects will not use a tail-recursive implementation.

Context

This was noticed by @datokrat while doing some benchmarks.

Expected behavior: Summing up lists of Nat and Int should be tail-recursive

Actual behavior: Crashes due to stack overflow

Versions

4.19.0-nightly-2025-03-30 on live.lean-lang.org

Impact

Add 👍 to issues you consider important. If others are impacted by this issue, please ask them to add 👍 to it.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.