Julia:显示函数体(查找丢失的代码) [英] Julia: show body of function (to find lost code)

查看:8
本文介绍了Julia:显示函数体(查找丢失的代码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 R 语言中,我可以声明一个函数并查看函数体,如下所示:

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)
}

这样的事情在 Julia 中也可以实现吗?我写了一个非常有用的函数,它仍然在内存中/可调用,但我忘记了我是怎么写的.我希望 Julia 中存在这样的方法,这样我就可以找出我是如何编写它的.

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.

推荐答案

对于包中定义的函数,可以使用less@less.前者采用函数名(并返回第一个定义,不一定是你想要的),后者,一个函数调用.

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)

但这不适用于您在 REPL 中定义的函数.对于那些,您可以使用 code_typed,但它只返回 AST(抽象代码的语法树),可读性较差.您还需要提供参数的类型,因为可以有多个同名的函数:您可以通过 methods 获取它们.

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))))

这篇关于Julia:显示函数体(查找丢失的代码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆