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

Using fold() and reduce() to compose objects creates deep call stacks #977

Open
bioball opened this issue Feb 21, 2025 · 0 comments
Open

Comments

@bioball
Copy link
Contributor

bioball commented Feb 21, 2025

This code will stack overflow:

class Num {
  value: Int
}

local numbers: List<Num> = IntSeq(0, 100000).map((i) -> new Num { value = i })

local adder = (numA: Num, numB: Num) -> new Num { value = numA.value + numB.value }

sum = numbers.reduce(adder).value

At the end of each iteration, the returned value from adder retains a lazy value. The resulting object, as a result, has a value member that recurses.

This type of code is less performant, and is also vulnerable to stack overflow exceptions. It's also very hard to understand why this is recursive. We should have some way to avoid deep call stacks here.

Note: a workaround is to force the computation with a let expression, e.g.

local adder = (numA: Num, numB: Num) ->
  let (result = numA.value + numB.value)
    new Num { value = result }
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