Working with code blocks

Live evaluation of code blocks

If you would like to show code as well as what the code outputs, you only need to specify where the script corresponding to the code block will be saved.

Indeed, what happens is that the code block gets saved as a script which then gets executed. This also allows for that block to not be re-executed every time you change something else on the page.

Here's a simple example (change values in a to see the results being live updated):

using LinearAlgebra
a = [1, 2, 3, 3, 4, 5, 2, 2]
@show dot(a, a)
println(dot(a, a))

You can now show what this would look like:

dot(a, a) = 72
72

Notes:

Lastly, it's important to realise that if you don't change the content of the code, then that code will only be executed once even if you make multiple changes to the text around it.

Here's another example,

for i โˆˆ 1:5, j โˆˆ 1:5
    print(" ", rpad("*"^i,5), lpad("*"^(6-i),5), j==5 ? "\n" : " "^4)
end

which gives the (utterly useless):

 *    *****     *    *****     *    *****     *    *****     *    *****
 **    ****     **    ****     **    ****     **    ****     **    ****
 ***    ***     ***    ***     ***    ***     ***    ***     ***    ***
 ****    **     ****    **     ****    **     ****    **     ****    **
 *****    *     *****    *     *****    *     *****    *     *****    *

note the absence of .jl, it's inferred.

You can also hide lines (that will be executed nonetheless):

using Random
@show randn(2)
randn(2) = [0.2972879845354616, 0.3823959677906078]

Including scripts

Another approach is to include the content of a script that has already been executed. This can be an alternative to the description above if you'd like to only run the code once because it's particularly slow or because it's not Julia code. For this you can use the \input command specifying which language it should be tagged as:

x = randn(5)
y = randn(5)

for i in 1:5
    println(rpad("*"^i, 10, '-'), round(dot(x, y), digits=1))
end

these scripts can be run in such a way that their output is also saved to file, see scripts/generate_results.jl for instance, and you can then also input the results:

*---------1.3
**--------1.3
***-------1.3
****------1.3
*****-----1.3

which is convenient if you're presenting code.

Note: paths specification matters, see the docs for details.

Using this approach with the generate_results.jl file also makes sure that all the code on your website works and that all results match the code which makes maintenance easier.