Documentation and documentation in Engee
Good documentation is the key to a good understanding and use of the code.
The Julia language makes it convenient to use and create documentation out of the box.
This notebook will cover:
- getting help in .ngscript
- getting help on the command line
- create your own documentation for
- functions
- global variables
- structures
- modules
A way to create and connect 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 in the documentation, and a syntax hint.
@doc sqrt
Getting help on the command line
Use a question mark on the command line to get help.:
?
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 string containing the information about the function itself before the function name.
If the function description is long, it is recommended to use triple double кавычки.
"Краткое описание функции, здоровающейся с пользователем"
function user_greeting(username::String)
return "Hello, $(username)!"
end
@doc user_greeting
Let's briefly look at why in order to use symbols \ and $ мы используем raw - литерал необработанных строк:
В LaTex мы используем $\nu$ для обозначения символа ню:
Здесь сразу может возникнуть множество проблем. Внутри " "
$means interpolation:\nmeans line separator.
Therefore "$\nu$" it cannot be executed correctly. However, this problem can be solved by using raw-lines
# "$\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, keep in mind about the questions производительности and their expediency использования
Let's consider the case when several global variables can be documented with a single reference at once.
"Ускорение свободного падения"
g_Earth, g_Moon
const g_Earth::Float64 = 9.81
const g_Moon::Float64 = 1.62
Now let's check that the same reference exists for two variables at once.:
@doc g_Earth
@doc g_Moon
Please note that const it means that the type of the variable is constant, but not its value.
- When changing the type, an ERROR will be caused.**
- When changing to a value of the same type, a WARNING will be displayed.
# g_Moon = "Moon"
println(g_Earth)
g_Earth = 32.
println(g_Earth)
Documenting structures
Let's have a set of identical shapes.
The task is to arrange the shapes on the plane in the most compact way. Then the structure will contain the center of mass and the angle of rotation of the figure relative to the horizontal.
As the [default constructor](https://ru.wikipedia.org/wiki/Constructor by silence) select GeomteryShape((x=0,y=0),α=0). You can read more about constructors in the 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
Please note that the objects of our structure are immutable after they are constructed. If mutable objects are required, they must be of the [mutable struct] type (https://engee.com/helpcenter/stable/ru/julia/manual/types.html#изменяемые-составные-типы ).
# 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
The TemperatureScales.jl file is located in the folder with this example. This file contains a module TemperatureScales.
To access its functions and variables, you must
- go to the folder using the command
cd(path), where the executable file is located (documentating.ngscript) (@__DIR__). The same path contains TemperatureScales.jl:
@__DIR__
cd(@__DIR__)
- Include this module in our script:
By running the commandinclude("Filename.jl")julia will "include" the text from the fileFilename.jlinto our current script and executes it. (Look at the 1st line of the fileTemperatureScales.jl). This means that objects from this file will become objects of 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 a keyword module, and is used with using or import.
using .TemperatureScales
To find out exactly what this module does, let's call the help for this module.:
@doc TemperatureScales
Let's find out how fahr2cels functions work.:
@doc fahr2cels
As you can see, the fahr2cels help indicates 2 methods. The first is when the argument is a number, and the second is when the argument is a string.
Now go to the command prompt and run
? fahr2cels
Pay attention to the last line:
Extended help is available with ??.
Now exit the help mode (by deleting ?)
And now enter
?? fahr2cels
Now we have received EXTENDED help.
Conclusions
Documentation in Engee is very flexible (Markdown, ) and maintains a large list of objects to be documented: functions, variables, structures, macros, and modules.
The inclusion of a custom module in the script was considered.