如何让用户自定义函数的说明(“文档字符串”)提供给朱莉娅REPL?

问题描述 投票:82回答:2

如何用户定义函数(比如f)有有意义的打印输出时使用经由REPL检查?for help(f)

例如想象我写了下面的函数

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

如果我加载此为茱莉亚会话并尝试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的平方”在某处写。我猜的答案,我的问题可以从问题的答案决定“哪里是什么地方的描述应被写的?”


举例来说,如果我想要做相同的蟒蛇,我可以定义函数,并把描述为一个文档字符串:

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

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

julia
2个回答
52
投票

您可以在朱莉娅版本0.4(10月2015)及以上使用@doc宏。

% 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.

编辑:正如由@Harrison高汀指出的,版本0.5和以上支持的缩写语法以及降价,乳胶,和其他一些东西:

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

还有更多的细节in the documentation


18
投票

在朱莉娅V0.5 +,你可以写函数定义上方的多行字符串。 (无需@doc了。)

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

有关正确格式化你的文档字符串的更多信息,请参阅官方Julia Documentation

© www.soinside.com 2019 - 2024. All rights reserved.