如何使用户定义的函数描述(“ docstring”)可用于 Julia REPL?

当使用 ?fhelp(f)通过 REPL 检查时,用户定义的函数(比如 f)如何具有有意义的打印输出

例如,假设我编写以下函数

function f(x::Float64, y::Float64)
return 2x - y^2
end

如果我把这个加载到一个 julia 会话并尝试 help(f),我会得到以下结果:

julia> help(f)
f (generic function with 1 method)

如果我想看到的是

julia> help(f)
f


Compute 2 times x minus y squared

写着“计算2乘以 x 减去 y 的平方”的地方。我猜我的问题的答案可以从“描述应该写在哪里?”这个问题的答案中确定


例如,如果我想在 python 中执行相同的操作,我可以定义函数并将描述作为 docstring:

def f(x, y):
"""
Compute 2 times x minus y squared
"""
return 2 *  x - y ** 2

当我从 IPython 中键入 help(f)f?时,它将使我的描述立即可用。

10656 次浏览

You can use the @doc macro in Julia versions 0.4 (Oct. 2015) and above.

% julia
_
_       _ _(_)_     |  A fresh approach to technical computing
(_)     | (_) (_)    |  Documentation: http://docs.julialang.org
_ _   _| |_  __ _   |  Type "?help" for help.
| | | | | | |/ _` |  |
| | |_| | | | (_| |  |  Version 0.4.0 (2015-10-08 06:20 UTC)
_/ |\__'_|_|_|\__'_|  |  Official http://julialang.org/ release
|__/                   |  x86_64-apple-darwin13.4.0


julia> @doc """
Compute 2 times x minus y squared.
""" ->
function f(x::Float64, y::Float64)
return 2x - y^2
end
f (generic function with 1 method)


julia> @doc f
Compute 2 times x minus y squared.

Edit: As pointed out by @Harrison Grodin, versions 0.5 and above support an abbreviated syntax as well as Markdown, LaTEX, and a few other goodies:

"""
Calculate the left Riemann sum[^1] approximating ``\int_a^b f(x) dx = F(b) - F(a).``


[^1]: Thomas G., Finney R. (1996), Calculus and Analytic Geometry, Addison Wesley, ISBN 0-201-53174-7
"""
function rs(a, b, d, f)
end

There are more details in the documentation.

In Julia v0.5+ (including more recent Julia Versions like 1.2+), you can write a multiline string above the function definition. (No need for @doc anymore.)

julia> """
cube(x)


Compute the cube of `x`, ``x^3``.


# Examples
```jldoctest
julia> cube(2)
8
```
"""
function cube(x)
x^3
end
cube


help?> cube
search: Cdouble isexecutable Ac_mul_B Ac_mul_Bc Ac_mul_B! Ac_mul_Bc! cumsum_kbn


cube(x)


Compute the cube of x, x^3.


Examples
≡≡≡≡≡≡≡≡≡≡


julia> cube(2)
8

For more information on properly formatting your docstrings, see the official Julia Documentation.