title: Constructing functions with multiple methods inside a closure, and the error "syntax: local variable T cannot be used in closure declaration"
body: <p>I'm working on a Julia function that constructs a function with multiple methods inside a closure and return that. To simplify (the actual construction involves multiple non-trivial custom types), it looks like this:</p>
  
  <pre><code>function constructF(g::Function, n::Int)
  
      v = [g]
      for i in 2:n
          gi(x) = ForwardDiff.derivative(v[i - 1], x)
          v = vcat(v, gi)
      end
  
      for T in (Int, Float64) # two types but possibly more
          function f(x::T)
              acc = T(0)
              for i in 1:n
                  acc += v[i](x)^i
              end
              acc
          end
      end
  
      return f
  end
  </code></pre>
  
  <p>This kind of code is not supported as of Julia 1.1.1 and gives me</p>
  
  <pre><code>ERROR: LoadError: syntax: local variable T cannot be used in closure declaration
  Stacktrace:
   [1] include(::String) at ./client.jl:403
   [2] top-level scope at none:0
  in expression starting at /home/me/code/lang/julia/test.jl:3
  </code></pre>
  
  <p>The alternative would be the below but results in duplicated code.</p>
  
  <pre><code>function constructF(n::Int)
  
      v = [g]
      for i in 2:n
          gi(x) = ForwardDiff.derivative(v[i - 1], x)
          v = vcat(v, gi)
      end
  
      function f(x::Int)
          acc = Int(0)
          for i in 1:n
              acc += v[i](x)^i
          end
          acc
      end
  
      function f(x::Float64)
          acc = Float64(0)
          for i in 1:n
              acc += v[i](x)^i
          end
          acc
      end
  
      # ....
  
      return f
  end
  </code></pre>
  
  <p>Is there a better way to write this? I've looked into metaprogramming but the documentation comes across as unintuitive and I'm not sure how to apply it here.</p>