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

2

19

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.

Olfe answered 6/10, 2014 at 19:42 Comment(2)
what do you get if you just type the name of the function into the Julia interpreter?Eastwood
(generic function with 1 method)Olfe
C
19

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))))
Calcifuge answered 6/10, 2014 at 23:57 Comment(2)
code_lowered (called the same way) may be closer to the original code than code_typed, but unfortunately both will be pretty far from it, and neither will give you something you can actually run (at least not without a great deal of trickery).Swizzle
When I use less(func), it's printed the code of the entire module where func was defined. Is there a way to have it print only the definition of the func? Does it depend on how func is imported? I'm running this in a JupyterLab notebook as well - perhaps that doesn't work well with less?Nozzle
S
-2

the answers said above are already good. I personally use the good old ctrl+r in the REPL and write the name of the function as you define it to find the block of code when you define your function.

Sauterne answered 4/8, 2022 at 14:46 Comment(1)
The other answers are not always "above". Sure, they are while you type your answer - but then they're sorted in the page once posted. Criteria are "Trending", "Highest score", "Date modified", "Date created". Your answer will be placed in the page according to this parameter.Recoil

© 2022 - 2024 — McMap. All rights reserved.