Somehow my code is so horrifying, Lean4 is able to evaluate it, the LSP says it works and the compiler gives an error. It is theoretically correct and the kernel accepts it, but the compiler isn't able to produce anything out of it. My awful code discovered a bug in Lean's compiler.
Thanks! I tried to make the code as ugly as possible for this sub.
Explanation (boring alert): Lean4 is a theorem checker, meaning you can prove things in code, and the compiler checks whether its a valid proof or not. What I did was essentially a proof by exhaustion of a naive implementation of TwoSum. Since the algorithm checks all possible pairs of numbers, meaning that if the algorithm finds a pair, that pair is the solution, otherwise there is no solution at all. The algorithm then (if successful) returns a pair and a proof that the pair is the solution. Somehow, whilst trying to make this code uglier I discovered a bug in the Lean compiler that allowed me to have a well-typed expression without the compiler knowing how to produce code for it. It allows me to evaluate expressions, but not compile them.
am I reading Lean problem statement correctly? when you return some(), you are not guaranteeing that it's the returned indexes that sum to the target, only that some such indexes exist?
Yeah so some _ => (∃ p : Fin n × Fin n, v[p.1] + v[p.2] = target ∧ p.1 ≠ p.2) becomes: some p => (v[p.1] + v[p.2] = target ∧ p.1 ≠ p.2)
and matching on pairs in the some case returns a different constructor: in the base case: ⟨some p, hsol⟩ => ⟨some (⟨0, h0⟩, p.2), hsol⟩ In the inductive case: ⟨some p, hsol⟩ => ⟨some (⟨i + 1, hip⟩, p.2), hsol⟩
which actually simplified my proof because I don't need to turn an already valid pair into a proof that a valid pair exists, I just have to propagate it.
Never tried it but seems interesting. I'm still learning Lean so I have just been following convention. I don't really like Lean's default syntax so thanks for the tip!
111
u/MistakeIndividual690 Sep 02 '26
I don’t know what Lean is but what for the love of god is this…
TwoSum is like eight lines in Python
But this is clearly the perfect post for this sub
35
u/JAMIEISSLEEPWOKEN Sep 02 '26
……you want a hashmap…?
10
u/NooneAtAll3 Sep 02 '26
am I reading Lean problem statement correctly? when you return some(), you are not guaranteeing that it's the returned indexes that sum to the target, only that some such indexes exist?