# Why Can not My Recursive Function Work?

**URL:** <https://discourse.julialang.org/t/why-can-not-my-recursive-function-work/51378>\
**Category:** General Usage\
**Tags:** question, function\
**Created:** [December 7, 2020, 6:41am UTC](https://discourse.julialang.org/t/why-can-not-my-recursive-function-work/51378 "2020-12-07T06:41:59Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![KyleJT](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kylejt/32/8929_2.png) [@KyleJT](https://discourse.julialang.org/u/KyleJT)\
**Post date:** [December 7, 2020, 6:41am UTC](https://discourse.julialang.org/t/why-can-not-my-recursive-function-work/51378/1 "2020-12-07T06:41:59Z")

</div>

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

```julia
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](https://discourse.julialang.org/u/sudete) suggest, I revised my code as followed:

```julia
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.

---

<div class="post-metadata">

**Author:** ![sijo](https://avatars.discourse-cdn.com/v4/letter/s/da6949/32.png) [@sijo](https://discourse.julialang.org/u/sijo)\
**Post date:** [December 7, 2020, 6:53am UTC](https://discourse.julialang.org/t/why-can-not-my-recursive-function-work/51378/2 "2020-12-07T06:53:04Z")

</div>

Executing your code I get

```julia
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:

```julia
    if length(b) == 1
        return b
    end

```

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

---

<div class="post-metadata">

**Author:** ![KyleJT](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kylejt/32/8929_2.png) [@KyleJT](https://discourse.julialang.org/u/KyleJT)\
**Post date:** [December 7, 2020, 7:04am UTC](https://discourse.julialang.org/t/why-can-not-my-recursive-function-work/51378/4 "2020-12-07T07:04:35Z")

</div>

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