Amazing! You can define a function using "do" and "end"

I did not know that you can define a function “func” using just “do” and “end”. This is amazing!!!

    @inline function PDFP_setDefaultPrecision(prec::Int)
        global DEFAULT_PRECISION[] = prec < 0 ? 0 : prec
    end

    function PDFP_temporarily_setDefaultPrecision(func::Function,prec::Int)
        olddefaultprec = PDFP_getDefaultPrecision()
        PDFP_setDefaultPrecision( prec )
        func()
        PDFP_setDefaultPrecision( olddefaultprec )
    end

And using it like this

julia> println("Default Precision is ",PDFP_getDefaultPrecision() )
Default Precision is 16

julia> PDFP_temporarily_setDefaultPrecision(4) do
           global result = inv([ PDFP(1) PDFP(2); PDFP(3) PDFP(4) ])   
       end;

julia> result
2×2 Array{PDFP,2}:
 PDFP(1, 0, [2, 0, 0, 0])   PDFP(0, 0, [1, 0, 0, 0])
 PDFP(0, 0, [1, 5, 0, 0])  PDFP(1, -1, [5, 0, 0, 0])
1 Like

:+1:

It’s explained in a bit more detail in the manual (perhaps that’s where you found it).

This is indeed quite useful to create more readable code. And this is the reason you’ll usually see function arguments first in the argument list (this trick only works with the first argument), and it’s a good practice to follow for code you write.

6 Likes