@@ -122,19 +122,19 @@ const FOLDL_RECURSION_LIMIT = Val(10)
122122_dec (:: Nothing ) = nothing
123123_dec (:: Val{n} ) where n = Val (n - 1 )
124124
125- function __foldl__ (rf, init, coll)
126- ret = iterate (coll)
127- ret === nothing && return complete (rf, init)
128- x, state = ret
129- val = @next (rf, init, x)
130- return _foldl_iter (rf, val, coll, state, FOLDL_RECURSION_LIMIT)
131- end
125+ @inline _iterate (iter, :: Unseen ) = iterate (iter)
126+ @inline _iterate (iter, state) = iterate (iter, state)
127+
128+ @inline __foldl__ (rf, init, coll) =
129+ _foldl_iter (rf, init, coll, Unseen (), FOLDL_RECURSION_LIMIT)
132130
133- @inline function _foldl_iter (rf, val:: T , iter, state, counter) where T
134- while (ret = iterate (iter, state)) != = nothing
131+ @inline function _foldl_iter (rf, val:: T , iter, state:: S , counter) where {T, S}
132+ while true
133+ ret = _iterate (iter, state)
134+ ret === nothing && break
135135 x, state = ret
136136 y = @next (rf, val, x)
137- counter === Val (0 ) || y isa T ||
137+ counter === Val (0 ) || y isa T || state isa S ||
138138 return _foldl_iter (rf, y, iter, state, _dec (counter))
139139 val = y
140140 end
@@ -145,13 +145,15 @@ __foldl__(rf, init, coll::Tuple) =
145145 complete (rf, @return_if_reduced foldlargs (rf, init, coll... ))
146146
147147# TODO : use IndexStyle
148- @inline function __foldl__ (rf, init, arr:: Union{AbstractArray, Broadcasted} )
149- isempty (arr) && return complete (rf, init)
150- idxs = eachindex (arr)
151- val = @next (rf, init, @inbounds arr[idxs[firstindex (idxs)]])
152- @simd_if rf for k in firstindex (idxs) + 1 : lastindex (idxs)
153- i = @inbounds idxs[k]
154- val = @next (rf, val, @inbounds arr[i])
148+ @inline __foldl__ (rf, init, arr:: Union{AbstractArray, Broadcasted} ) =
149+ _foldl_array (rf, init, arr, firstindex (arr), FOLDL_RECURSION_LIMIT)
150+
151+ @inline function _foldl_array (rf, val:: T , arr, n, counter) where T
152+ @simd_if rf for i in n: lastindex (arr)
153+ y = @next (rf, val, @inbounds arr[i])
154+ counter === Val (0 ) || y isa T ||
155+ return _foldl_array (rf, y, arr, i + 1 , _dec (counter))
156+ val = y
155157 end
156158 return complete (rf, val)
157159end
0 commit comments