Julia: sum_kbn for iterators

Created on 30 Jan 2017  路  11Comments  路  Source: JuliaLang/julia

Add sum_kbn(itr) and sum_kbn(f, itr) methods.

https://discourse.julialang.org/t/why-sum-kbn-cant-sum-generators/1717/2

collections good first issue maths

Most helpful comment

I would like to work on this issue !

Would this be the right approach to make it work for iterable collection by converting the iterable collection first into array and then using the existing function
function sum_kbn{T<:AbstractFloat}(A::AbstractArray{T}) ?
Or is there a more better and efficient approach ?

All 11 comments

I would like to work on this issue !

Would this be the right approach to make it work for iterable collection by converting the iterable collection first into array and then using the existing function
function sum_kbn{T<:AbstractFloat}(A::AbstractArray{T}) ?
Or is there a more better and efficient approach ?

@kvmanohar22 Converting to an array will not be efficient. Also T <: AbstractFloat is not ideal I think, since one might want to use sum_kbn with e.g. complex numbers. I would go with something like

function sum_kbn(A)
    T = eltype(A)
    c = r_promote(+, zero(T)::T)
    if isempty(A)
        return c
    end
    i = start(A)
    Ai, i = next(A, i)
    s = Ai + c
    while !(done(A, i))
        Ai, i = next(A, i)
        t = s + Ai
        if abs(s) >= abs(Ai)
            c += ((s-t) + Ai)
        else
            c += ((Ai-t) + s)
        end
        s = t
    end
    s + c
end

@jw3126 It looks very similar to the original implementation for arrays. Is there a way to avoid code duplication? Maybe sum_kbn(A::AbstractArray) should fall back on the implementation for iterators?

@cossio This should subsume the array version, so the array version can be deleted.

In that case the prototype of the function would be something like
function sum_kbn{T<:AbstractFloat}(A::Base.Generator{FloatRange{Float64}, Type{T}}) ,
how would this subsume the array version ?

I would just ducktype. E.g. go with function sum_kbn(A) and not function sum_kbn(A::SomeLongType). So it works even with user defined iterator types.

@jw3126 Iterating an array with next, done is as fast as linear indexing?

@cossio This should be as fast as possible, since it is just raw iteration and no index lookup etc.

@jw3126 , could you brief me on how you would ducktype here ?
I'm quite new to this concept.

Duck typing means you don't specify the type of A in function sum_kbn(A) at all.

This feature has now been added in PR #20336

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wilburtownsend picture wilburtownsend  路  3Comments

TotalVerb picture TotalVerb  路  3Comments

iamed2 picture iamed2  路  3Comments

i-apellaniz picture i-apellaniz  路  3Comments

dpsanders picture dpsanders  路  3Comments