Value assignment of compound expression

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Value assignment of compound expression

wangrui


Hi guys,

I am new to Julia and learning from scratch. I ran into the compound expression like this:


tri=base=5;height=10;1/2*base*height


This is to calculate the triangle area. The result is right. But I am concerned about the value of "tri". What is it after the calculation. Shouldn't it be 25? Julia told me it is 5!!

Can anybody help me with this?
Reply | Threaded
Open this post in threaded view
|

Re: Value assignment of compound expression

Valentin Churavy
Welcome to Julia.

Similar to other programming language you can (but you do not need to) use a semicolon as a separator between statements.
So your code example is equivalent to:

tri=base=5
height
=10
1/2*base*height

so there is no assignment to tri after the first line, and thus the value is equal to 5.
Reply | Threaded
Open this post in threaded view
|

Re: Value assignment of compound expression

David P. Sanders
In reply to this post by wangrui


El jueves, 10 de noviembre de 2016, 0:43:19 (UTC-5), [hidden email] escribió:


Hi guys,

I am new to Julia and learning from scratch. I ran into the compound expression like this:


tri=base=5;height=10;1/2*base*height


This is to calculate the triangle area. The result is right. But I am concerned about the value of "tri". What is it after the calculation. Shouldn't it be 25? Julia told me it is 5!!

Can anybody help me with this?

If you actually want the result assigned to tri, you can do it by adding parentheses to what you wrote:

julia> tri1 = (base = 5; height = 10; 0.5 * base * height)
25.0

julia> tri1
25.0

(Note that the code is more readable with more space.)

However, what you are really trying to do is make something that, given a base and a height, calculates the area,
i.e. a function. So it is more natural (and reusable) to do something like this:


julia> triangle_area(base, height) = 0.5 * base * height
tri (generic function with 1 method)

julia> base, height = 5, 10
(5,10)

julia> triangle_area(base, height)
25.0

This has the advantage that you can also reuse the variables base and height later. 

(Note also that `base` is a function defined in the Julia standard library (which itself is called `Base`!)
and this code overwrites it when run in global scope.)