r/programminghorror 9h ago

Lean4 Finally solved Two Sum!

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.

77 Upvotes

7 comments sorted by

47

u/MistakeIndividual690 8h ago

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

40

u/swagnation77 8h ago

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.

3

u/TLJGame 8h ago

The what I’m assuming are variable names just makes this 10x worse

4

u/swagnation77 8h ago

I'm sorry.

21

u/JAMIEISSLEEPWOKEN 9h ago

……you want a hashmap…?

8

u/swagnation77 8h ago

lmao yeah if I did a hashmap the solution would've been better, but the proofs would've taken me 10x as long. (I spent two days on a single algorithm)