Documentation and documentation in Engee¶
Good documentation is the key to quality understanding and use of code. The Julia language makes it easy to use and create documentation out-of-the-box.
This notebook will cover:
- getting help in .ngscript
- getting help on the command line
- creating your own documentation for
- functions
- global variables
- structures
- modules
The method of creating and connecting your own module will also be considered.
Getting Help in .ngscript¶
To get help in .ngscript you need to use the macro
@doc
Consider getting help for sqrt
.
Note the use of Markdown, $\LaTeX$ and syntax highlighting in the documentation.
@doc sqrt
Getting help at the command line¶
Use a question mark to get help on the command line:
?
😊😊😊😊😊 if you want to expand your knowledge about using the command line - read the document to the end 😊😊😊.
Creating your own documentation¶
Documenting functions.¶
In order to add your own documentation to a function, you must add a line containing the information about the function before the function name.
If the function description is long, it is recommended to use triple double quotes.
"Краткое описание функции, здоровающейся с пользователем"
function user_greeting(username::String)
return "Hello, $(username)!"
end
@doc user_greeting
Let's briefly consider why we need to use the characters \
and $
мы используем raw
- литерал необработанных строк:
В LaTex мы используем $\nu$
для обозначения символа ню: $\{nu$
Здесь сразу может возникнуть множество проблем. Внутри " "
$
means interpolation:\n
means line separator.
Therefore. "$\nu$"
will not be able to be executed correctly. However, this problem can be solved by using raw
-strings
# "$\nu$" # вызовет ошибки
@show raw"$\nu$";
@doc raw"""
Документация, содержащая:
1. Markdown:
- маркеры списка
- [внешние ссылки](https://engee.com/helpcenter/stable/ru/julia/stdlib/Markdown.html)
2. Встроенный $\LaTeX$ (inline) $\frac{\sqrt{\pi}}{2}$ и отдельной формулой:
```math
\int \limits_{-\infty}^\infty e^{-x^2}\,dx = \sqrt{\pi}
```
## Смотреть также
[`документирование`](https://engee.com/helpcenter/stable/ru/julia/manual/documentation.html
), [`функции`](https://engee.com/helpcenter/stable/ru/julia/manual/functions.html)
"""
function foo()
return nothing
end
@doc foo
Documenting global variables¶
When using global variables, be aware of performance issues and the appropriateness of their use
Consider the case where multiple global variables can be documented with a single reference
"Ускорение свободного падения"
g_Earth, g_Moon
const g_Earth::Float64 = 9.81
const g_Moon::Float64 = 1.62
Now let's check that the same help exists for two variables at once:
@doc g_Earth
@doc g_Moon
Note that const
means the constancy of the variable's type, but not its value.
- If the type is changed, an ** ERROR** will be invoked
- When changing to a value of the same type, WARNING will be called.
# g_Moon = "Moon"
println(g_Earth)
g_Earth = 32.
println(g_Earth)
Documenting Structures¶
Suppose there is a set of identical shapes.
The problem is to arrange the figures on the plane in the most compact way. Then the structure will contain centre of mass and angle of rotation of the figure relative to the horizontal.
As default constructor we will choose
GeomteryShape((x=0,y=0),α=0)
. You can read more about constructors in documentation.
@doc """
GeometricShape((x=X,y=Y),α)
Геометрическая фигура
- `center_of_mass`: (x=X,y=Y) - кортеж координат центра масс
- `orientation`: α - угол поворота фигуры относительно горизонтали
## Пример:
GeometricShape((x=1., y=2.), 3.)
## Возможные ошибки
1.
```julia-repl
julia> GeometricShape((4.,5.),6.)
ERROR: MethodError: no method matching GeometricShape(::Tuple{Float64, Float64}, ::Float64)
Closest candidates are:
GeometricShape(::@NamedTuple{x::Float64, y::Float64}, ::Any)
```
**Решение:** в кортеже нужно явно указать имена полей: `GeometricShape((x=4., y=5.), 6.)`
2.
```julia-repl
julia> GeometricShape((x=1,y=2),3.)
ERROR: MethodError: no method matching GeometricShape(::@NamedTuple{x::Int64, y::Int64}, ::Float64)
Closest candidates are:
GeometricShape(::@NamedTuple{x::Float64, y::Float64}, ::Any)
```
**Решение:** передавайте в качетсве параметров значения типа `Float64`, а не `Int64`: GeometricShape((x=1.,y=2.),3.)
"""
struct GeometricShape
center_of_mass::NamedTuple{(:x,:y),Tuple{Float64,Float64}}
orientation::Float64
GeometricShape() = new((x=0,y=0),0) # конструктор по умолчанию
GeometricShape((X,Y)::NamedTuple{(:x,:y),Tuple{Float64,Float64}},α)=new((x=X,y=Y),α)
end
GeometricShape((x=4.,y=5.),6.)
@doc GeometricShape
GeometricShape()
first_shape = GeometricShape((x=1.,y=2.),3.)
first_shape.center_of_mass.y
Note that objects of our structure are immutable after their construction. If the use of mutable objects is required, they must be of type mutable struct.
# first_shape.orientation = 4. # ОШИБКА: нельзя менять уже созданный объект
Documenting macros¶
"Макрос, здоровающийся с пользователем"
macro hellouser(username) # создание макроса
println("Hello, $(username)!")
end
@hellouser "Peter" # применение макроса
To get help for a macro, you must first write @
, and then enter the macro name:
@macrosname
@doc @hellouser
Creating and documenting a module¶
In the folder along with this example is the file TemperatureScales.jl. This file contains the module TemperatureScales
.
To access its functions and variables, you need to
- Go to the folder using the command
cd(path)
, where the executable file (documentating.ngscript) (@__DIR__
) is located. The same path contains TemperatureScales.jl:
@__DIR__
cd(@__DIR__)
- Include this module in our script:
By executing the command
include("Filename.jl")
, julia will "include" the text from the fileFilename.jl
into our current script and execute it. (Look at the 1st line of the fileTemperatureScales.jl
). This means that objects from this file will become objects in our file.
include("TemperatureScales.jl")
println(variable_from_TemperatureScales)
But our task is to use the module from this file. The module is created using the keyword module
, and used using using
or import
.
using .TemperatureScales
To find out what exactly this module does, let's call the module help:
@doc TemperatureScales
Let's find out how fahr2cels functions work:
@doc fahr2cels
As you can see, the fahr2cels help specifies 2 methods. The first when the argument is a number, and the second when the argument is a string.
Now go to the command prompt and run
? fahr2cels
Note the last line:
Extended help is available from ??
.
Now exit help mode (by deleting ?
)
And now enter
?? fahr2cels
We now have an EXPANDED reference 😊😊😊😊.
Conclusions¶
Documentation in Engee is very flexible (Markdown, $\LaTeX$) and supports a large list of objects to be documented: functions, variables, structures, macros and modules.
The inclusion of a custom module in a script was examined.