Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: show body of function (to find lost code)

Tags:

function

r

julia

In the R-language I am able to declare a function and to see the body of the function like so:

> megafoobar = function(x){ return(x + 10000 )}
> body(megafoobar)
{
    return(x + 10000)
}

Is something like this also possible in Julia? I wrote a function that was very useful and it is still in memory/callable but I forgot how I wrote it. I am hoping such a method exists in Julia so I can find out how I wrote it.

like image 951
cantdutchthis Avatar asked Oct 06 '14 19:10

cantdutchthis


1 Answers

For functions defined in a package, you can use less or @less. The former, takes a function name (and returns the first definition, which need not be the one you want), the latter, a function call.

less(less)         # First definition of less, 
                   # with signature (String,Integer)
@less less(less)   # Definition of less(f::Callable)

But this will not work with functions you defined yourself in the REPL. For those, you can use code_typed, but it only returns the AST (abstract syntax tree) of your code, which is less readable. You also need to provide the type of the arguments, because there can be several functions with the same name: you can get them with methods.

f(x::Number) = x + 1
f(x::AbstractArray) = length(x)

methods(f)
# 2 methods for generic function "f":
# f(x::Number) at none:1
# f(x::AbstractArray{T,N}) at none:1

code_typed(f,(Number,))  # Give the argument types as a tuple
# 1-element Array{Any,1}:
#  :($(Expr(:lambda, {:x}, {{},{{:x,Number,0}},{}}, :(begin  # none, line 1:
#         return x::Number + 1
#     end))))
like image 86
Vincent Zoonekynd Avatar answered Oct 11 '22 08:10

Vincent Zoonekynd