Why Can not My Recursive Function Work?

I want to write a function to add all the arguments, using a recursive function as followed:

function add_Varargs(b...)
    if length(b) == 1
        return b
    else
        t=b[1:end-1]
        println(b[end])
        return b[end]+add_Varargs(t...)
    end
end

xx = (1,2,3)
add_Varargs(xx...)

But it doesn’t work. Could anyone help me to figure out my fault, and offer me the right and proper one?

Thank you.


Final Solution:

As @sudete suggest, I revised my code as followed:

function add_Varargs(b...)
    if length(b) == 1
        return b[1] # the original code did wrongs here.
    else
        t=b[1:end-1]
        println(b[end])
        return b[end]+add_Varargs(t...)
    end
end

xx = (1,2,3)
add_Varargs(xx...)

And this works! thank you.

Executing your code I get

julia> add_Varargs(xx...)
3
2
ERROR: MethodError: no method matching +(::Int64, ::Tuple{Int64})

So it works at the beginning but fails on the + with the last call, because it cannot add an integer to a tuple. Why is it trying to add a tuple? It’s here:

    if length(b) == 1
        return b
    end

This returns a tuple of length 1 instead of a number.

2 Likes

Following your advice, I correct my original code, and it works in the end. Thank you for your help.

1 Like