leanprover / leanprover/lean4

Elaboration failure from interaction between `GetElem?` and default instances

Open
#5,414 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Description

If the index to xs[...]? notation is a natural number literal, the GetElem? instance synthesis is deferred until later. This can result in elaboration failure since the return value of xs[...]? might be forced to be something unexpected.

Context

This came up on Zulip when a user was asking about why a monadic expression wasn't elaborating.

Steps to Reproduce

Consider

def justFirst (xs : List α) : Option α :=
  xs[0]? >>= fun first => first

Expected behavior: This elaborates.

Actual behavior: There is an error on xs[0]? with "failed to synthesize GetElem? (List α) ℕ (Option α) ?m".

Versions

4.12.0-rc1, macOS 15.0, m3

Additional Information

The reason this doesn't succeed is that the OfNat instance for 0 doesn't resolve until default instances are considered. By this point fun first => first elaborates, forcing the type of xs[0]? to be Option (Option α).

One solution to this would be to have a separate typeclass whose purpose is to specify the element type of a collection, independent of the index type. For example elements of List α have type α. This would let us solve for the return type before resolving the index type.

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.

Research direction

Start by reproducing the justFirst example from the issue in Lean 4 and confirm the GetElem? synthesis error. The issue names no repository files or tests; done means the example elaborates successfully without forcing the result to an unintended nested Option type.

Written by the indexing model from the issue text.

Assessment

Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.