Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Advent of Codon and Capturing Loop Variables #611

Open
AndreiMoraru123 opened this issue Dec 3, 2024 · 0 comments
Open

Advent of Codon and Capturing Loop Variables #611

AndreiMoraru123 opened this issue Dec 3, 2024 · 0 comments

Comments

@AndreiMoraru123
Copy link

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 ans

which 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 ans

which 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant