A variable is a name bound to a value:
a = 3
These names are extremely flexible & can use any Unicode character.
The only rules are:
They must begin with a letter or an underscore (a few of the Unicode characters are also accepted)
They cannot be the names of built-in statements such as if
, do
, try
, else
The Julia Style Guide recommends the following conventions:
use lower case
word separation can be indicated by underscores, but better not use them if the names can be read easily enough without them
In an interactive session, Julia returns the value of an expression (even the assignment to a variable), unless you add a semi-colon at the end:
b = "Hello, World!";
To print a value in the REPL or in Jupyter, you only need to call it:
a
If you want to print it while running a script however, you need to use the println()
function:
println(a)
You can reassign new values to variables:
a = 3;
a = -8,2;
a
You can define multiple variables at once:
a, b, c = 1, 2, 3
b
Variables in Julia are case-sensitive & can include Unicode characters:
δ = 8.5;
Built-in keywords are not allowed. Neither are built-in constants & keywords in use in a session:
false = 3;
> ERROR: syntax: invalid assignment location "false"
The keyword ans
is a variable which, in the REPL, automatically takes the value of the last computation:
a = 3
typeof(ans)
ans + 1
b = "test"
typeof(ans)
Type safety (catching errors of inadequate type) performed at compile time
Type safety done at runtime
Julia’s type system is dynamic (types are unknown until runtime), but types can be declared, optionally bringing the advantages of static type systems
This gives users the freedom to choose between an easy and convenient language, or a clearer, faster, and more robust one (or a combination of the two)
At the bottom: concrete types
Above: abstract types (concepts for collections of concrete types)
At the top: the Any
type, encompassing all types
Done with ::
<value>::<type>
Example:
2::Int
This works:
2::Int
We get an error message here:
2.0::Int
function floatsum(a, b)
(a + b)::Float64
end
This works:
floatsum(2.3, 1.0)
function floatsum(a, b)
(a + b)::Float64
end
We get an error message here:
floatsum(2, 4)
To know the type of an object, use typeof
:
typeof(2)
typeof(2.0)
typeof("Hello, World!")
typeof(true)
typeof((2, 4, 1.0, "test"))
When it makes sense, you can also convert types:
Int(2.0)
Char(2.0)