google / google/jsonnet

max stack frame exceeded when foldl with object/array as accumulated value

Open
#952 1 comment 1 reaction 0 assignees View on GitHub
enhancement
Dominant language
Jsonnet
Stars
7.6k
Forks
475
PR merge metrics
No merged PRs in 30d

Description

The following code would fail (i know this is not meaningful, but just act as a reduced example)
```
std.foldl(function(p, c) [p[0]+1, c], std.range(0, 2000), [0, 0])
```
Output:
```
Error: RUNTIME ERROR: max stack frames exceeded.
```

I thought this was due to lack of tail recursion optimization, but that's not the case if the accumulated value is a string.
Hence the following code is fine by writing a new foldl wrapper (workaround, so accumulated value is a string instead)

```
local foldl(f, arr, init) =
std.parseJson(std.foldl(function(p, curr)
std.manifestJson(f(std.parseJson(p), curr))
, arr, std.manifestJson(init)));

foldl(function(p, c) [p[0]+1, c], std.range(0, 2000), [0, 0])
```
Output:
```
[
2001,
2000
]
```

I found this problem as I was trying to using jsonnet to solve advent of code (https://gist.github.com/bigdrum/1980304abc6561d01f12dad50aa73538). But I would not be surprised if this happens in real world usage.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.