# Recursive call with ForwardDiff

**URL:** <https://discourse.julialang.org/t/recursive-call-with-forwarddiff/35678>\
**Category:** Optimization (Mathematical)\
**Created:** [March 7, 2020, 8:34am UTC](https://discourse.julialang.org/t/recursive-call-with-forwarddiff/35678 "2020-03-07T08:34:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![edljk](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/edljk/32/2429_2.png) [@edljk](https://discourse.julialang.org/u/edljk)\
**Post date:** [March 7, 2020, 8:34am UTC](https://discourse.julialang.org/t/recursive-call-with-forwarddiff/35678/1 "2020-03-07T08:34:05Z")

</div>

Dear all,  
I considered the following piece of code. The Forward package is impressive in its flexibility! Nevertheless, I wonder if I am not missing some obvious optimization? Any suggestion are welcome.

```julia
using ForwardDiff
n = 10_000
uv = [[randn(), randn()] for k = 1:n]
function recfl(uv, fl, ∇fl)
    if length(fl) == 1
        return fl[1](uv) + ∇fl[1](uv)[2]
    else
        flv = @view fl[2:end]
        ∇flv = @view ∇fl[2:end]
        return fl[1](uv) + ∇fl[1](uv)[1] * recfl(uv, flv, ∇flv)
    end
end
fl = [y -> cos(y[1] * y[2]), y -> sin(y[1] + y[2]), y -> atan(y[1] - 3)]
∇fl = [y -> ForwardDiff.gradient(f, y) for f ∈ fl]
recfls = uv -> recfl(uv, fl ,∇fl)
@time ∇ffD = ForwardDiff.gradient.(recfls, uv);

```
