The World’s Largest Online Community for Developers
This is an example from a book I am reading:
volume = begin len = 10 breadth = 20 height = 30 len * breadth * height end
Why do I need compound expressions?? I could just write
volume = 10 * 20 * 30 or
volume = len * breadth * height or write a function for that or an anonymous function...
Why do I use
end? Or the probably better question: When do I use them, as I guess the example above from the book is probably not very good.
I guess there are many situations in which
begin ... end blocks are handy, but as you noted you can often also achieve a similar effect with other constructs, such as functions, etc.
begin ... end blocks be used for?
heightwill only exist within the block and not pollute the surrounding namespace.
@inbounds begin <all my code without bounds checking goes here> endor wrapping a
@time begin ... endaround a piece of code.
begin ... enddoes not introduce a local scope, but the argument holds for the similar
let ... endblock.)
In particular the second point is what I use them for in my codes.
To generalize what everyone else has said: blocks allow you to convert a list of statements (syntactic "phrases" that have no values, i.e., can't be assigned) to one expression (a "phrase" that represents values and can be assigned).
For example, while you shouldn't, you can write
x = begin s = 0 for i = 1:10 s += i^2 end s end
x to the result of a looping operation. (With the restriction that the last statement in the sequence must actually be an expression -- otherwise, you would have no value for the expression.)
A legitimate use case of this is generated code. For example, you might turn
x = @somthing bla blub
x = begin (stuff involving bla and blub) end
transparently to the user, while the
@something can freely generate any language constructs.
Or if you want to write an anonymous function with a longer body (and not use the
f = x -> begin ... end
One use for these blocks is in comprehensions:
A = [ begin x = y^2 x - x^2 + 2 end for y = 1:5 ]
You could make a function and use it inside the comprehension instead, but sometimes this is convenient. It’s used whenever you want to use a multiline block of code somewhere, eg to pass as an argument to a macro (which is very commonly used for
@testset from the Test standard library).
Simply put: “begin” just denotes a code block (see the docs on this: https://docs.julialang.org/en/v1/base/base/#begin).
In the example above, it’s not clear that there is any value to using a begin block vs declaring a function.
I don’t see that keyword being used very much in code and I personally have never used it in practice. My suggestion so to just use a function as it will do the same thing.