Julia is a dynamic language. You don't need type declarations, and can change variable types dynamically and interactively.
For working with simple numbers, arrays, and strings, its syntax is superficially similar to Matlab, Python, and other popular languages.
In order to execute the "In" cells, select the cell and press Shift-Enter, or press the Play button above. To run the entire notebook, navigate to Cell and then click Run All.
In [1]:
A = rand(10,300)
Out[1]:
It has all of the usual built-in Matlab/Numpy-like linear-algebra and vector functions:
In [2]:
b = rand(10)
x = A \ b
B = A' * A
erf(eigvals(B)) - 2x.^2 + 4x - 6
Out[2]:
Complex numbers and arbitrary-precision arithmetic (via MPFR), of course.
In [3]:
cos(big(3 + 4im))
Out[3]:
All strings are UTF-8 encoded Unicode by default (UTF-16 and UTF-32 also supported):
In [4]:
matchall(r"\s[a-z]+", "α is a Grëék letter") # regex search of a Unicode string
Out[4]:
Like Python 3, variable names can be Unicode, but Julia allows a somewhat wider range of codepoints in identifiers, which can be typed by LaTeX-like tab-completion \alpha[TAB]\hat[TAB]_2[TAB]\prime.
In [5]:
α̂₂′ = 7
ħ = 6.62606957e-34 / 2π
ẋ = ħ * α̂₂′
Out[5]:
Unlike Python 3, Unicode math operators are parsed as infix operators, which are available for user-defined meanings:
In [6]:
≪(x,y) = x < 0.1*y
50 ≪ 100, 5 ≪ 100, 5 ≤ 50
Out[6]:
In [7]:
const ⊗ = kron
eye(2,2) ⊗ rand(2,2)
Out[7]:
Functions can be defined in several ways, and don't require type-declarations.
In [8]:
# verbose form:
function foo(x)
return x + 1
end
# one-line form:
foo(x) = x + 1
# anonymous function
x -> x + 1
Out[8]:
The first time you call a function with arguments of a particular type, Julia JIT-compiles that function specialized for that type with LLVM, which is then cached for subsequent calls for the same types.
In [9]:
foo(3) # compiles foo for Int arguments
Out[9]:
In [10]:
foo(7) # re-uses compiled foo(Int)
Out[10]:
In [11]:
foo(7.3) # compiles a different version for Float64 arguments
Out[11]:
In [12]:
foo([1,2,7,9]) # compiles a different version for Array{Int,1} arguments
Out[12]: