Skip to content

Advent of Codon and Capturing Loop Variables #611

@AndreiMoraru123

Description

@AndreiMoraru123

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions