Skip to content

Commit

Permalink
[Utilities] use foldl to avoid StackOverflow (#2290)
Browse files Browse the repository at this point in the history
  • Loading branch information
blegat authored Sep 24, 2023
1 parent c059b17 commit ee780ba
Showing 1 changed file with 5 additions and 12 deletions.
17 changes: 5 additions & 12 deletions src/Utilities/operate.jl
Original file line number Diff line number Diff line change
Expand Up @@ -323,12 +323,7 @@ end
### 1c: operate(+, T, args...)

function operate(::typeof(+), ::Type{T}, f, g, h, args...) where {T<:Number}
ret = operate(+, T, f, g)
ret = operate!(+, T, ret, h)
for a in args
ret = operate!(+, T, ret, a)
end
return ret
return operate!(+, T, operate(+, T, f, g), h, args...)
end

### 2a: operate(::typeof(-), ::Type{T}, ::F)
Expand Down Expand Up @@ -1173,12 +1168,10 @@ end
### 1c: operate!(+, T, args...)

function operate!(::typeof(+), ::Type{T}, f, g, h, args...) where {T<:Number}
ret = operate!(+, T, f, g)
ret = operate!(+, T, ret, h)
for a in args
ret = operate!(+, T, ret, a)
end
return ret
# In order to improve performance and avoid a `StackOverflow` if there are
# too many arguments, `foldl` does not do recursion and fall back to a
# `for` loop if there are too many arguments.
return foldl((x, y) -> operate!(+, T, x, y), (f, g, h, args...))
end

### 2a: operate!(::typeof(-), ::Type{T}, ::F)
Expand Down

0 comments on commit ee780ba

Please sign in to comment.