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

Open
opened 2025-12-30 01:23:11 +01:00 by adam · 0 comments
Owner

Originally created by @bioball on GitHub (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 }
Originally created by @bioball on GitHub (Feb 21, 2025). This code will stack overflow: ```pkl 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. ```pkl local adder = (numA: Num, numB: Num) -> let (result = numA.value + numB.value) new Num { value = result } ```
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/pkl#285