Revealing the definition of an anonymous function


#1

When an anonymous function is assigned to a variable, I wonder if there is a way to retrieve the definition of the anonymous function from the variable.

Consider the following scenario. Let’s say I have an array of anonymous functions:

julia> farray = [x->2x, x->√x, x->x^2]
3-element Array{Function,1}:
 #1
 #2
 #3

Later I retrieve these functions from the array and evaluate them, but one function produces an error:

julia> for f = farray
           f(-1)
       end
ERROR: DomainError:
Stacktrace:
 [1] (::##2#5)(::Int64) at ./REPL[0]:1
 [2] macro expansion at ./REPL[1]:2 [inlined]
 [3] anonymous at ./<missing>:?

To figure out which function is the culprit, I print out the function information before evaluation:

julia> for f = farray
           println("f = $f")
           f(-1)
       end
f = #1
f = #2
ERROR: DomainError:
Stacktrace:
 [1] (::##2#5)(::Int64) at ./REPL[0]:1
 [2] macro expansion at ./REPL[2]:3 [inlined]
 [3] anonymous at ./<missing>:?

The result shows that the culprit is the anonymous function tagged with #2, but from this it is difficult to figure out what the function is. Is there a way to retrieve the definition of the function #2 here?


#2

For a simple case like your example:

julia> @code_lowered(farray[2](-1.0))
LambdaInfo template for (::##4#7)(x) at REPL[4]:1
:(begin 
        nothing
        return √x
    end)


#3

Great! Thanks a lot!!

For completeness, I was able to printout the @code_lowered outputs inside the for loop as follows:

julia> for f = farray
           println("$(@code_lowered f(-1))")
           f(-1)
       end
CodeInfo(:(begin
        nothing
        return 2 * x
    end))
CodeInfo(:(begin
        nothing
        return √x
    end))
ERROR: DomainError:
Stacktrace:
 [1] (::##18#21)(::Int64) at ./REPL[42]:1
 [2] macro expansion at ./REPL[46]:3 [inlined]
 [3] anonymous at ./<missing>:?

From this result, we can see that the √x is the function that raises the error.