Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why compound expressions?

Tags:

julia

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.

like image 271
Georgery Avatar asked Mar 07 '20 14:03

Georgery


1 Answers

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
like image 74
phipsgabler Avatar answered Oct 13 '22 22:10

phipsgabler