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 begin
and 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.
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
to assign 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
into
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 function
form):
f = x -> begin
...
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With