Why compound expressions?

Georgery :

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.

crstnbr :

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.

What could begin ... end blocks be used for?

  • To simply "contain" variables and their names: len, breadth, and height will only exist within the block and not pollute the surrounding namespace.
  • To apply macros to a block of code rather then individual statements. For example @inbounds begin <all my code without bounds checking goes here> end or wrapping a @time begin ... end around a piece of code.
  • To create a local scope in a surrounding global scope (to avoid global scope confusions for example). (Note that as has been pointed out in the comments begin ... end does not introduce a local scope, but the argument holds for the similar let ... end block.)

In particular the second point is what I use them for in my codes.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33165&siteId=1