-
Notifications
You must be signed in to change notification settings - Fork 582
Description
Hi again folks, I'm doing Advent of Code this year to try out Codon.
Today, I discovered that Codon does not capture loop variables.
For instance, in Python, for this piece of code:
fns = []
for i in range(5):
fns.append(lambda: print(i))
[f() for f in fns]you'd canonically get a reference for the loop variable:
❯ python capture.py
4
4
4
4
4
using codon you do not:
❯ codon run -release capture.py
0
1
2
3
4
I appreciate that this choice is intentional, to enable loop parallelism via the convenient @par
Now for the AoC part of the story, which I should skip for brevity, in Python, you can naturally control flow via global states like this:
state = True
ans = 0
for _, kind, value in instructions:
if kind == "do":
state = True
elif kind == "dont":
state = False
elif kind == "mul" and state:
ans += value
return answhich for the test sample
xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))
returns:
❯ python solution.py
48
And now for the problem: Codon cannot capture the state inside the loop branching:
❯ codon run -release solution.py
NameError: variable 'state' not yet defined
Raised from: __internal__.undef:0
/home/andrei/.codon/lib/codon/stdlib/internal/internal.codon:484:13
[1] 42058 IOT instruction (core dumped) codon run -release solution.py
So what I had to do instead was force state on the heap (at least I think so?) to give it a stable memory location:
state = [True]
ans = 0
for _, kind, value in instructions:
if kind == "do":
state[0] = True
elif kind == "dont":
state[0] = False
elif kind == "mul" and state[0]:
ans += value
return answhich only then works:
❯ codon run -release solution.py
48
Do you think there is/should be a better way to handle this?
Here is the whole code and input for reference:
https://github.com/AndreiMoraru123/aoc/blob/master/2024/d03/solution.py