A syntax bridge before the performance story
Four traps: arrays start at 1, blocks close with
end, the dot, functions not classes.
▶ Script: 0_julia_basics.jl · Notebook: 0_julia_basics.jl
⬅ Previous: Overview · Next: 1 — Interpreted vs compiled ➡
Assign with =, no declaration.
typeof(x)= Python’stype(x).
^. Bet first: what does 2**10 do?÷? Next slide.▶ Script: cell “Numbers” — try
2**10.
\name then TAB
2αis2 * α: formulas map straight to code.
▶ Script: cell “Unicode & juxtaposition”.
a, b = 3, 4
"Hello, $name" # "Hello, Ada"
"$a + $b = $(a + b)" # "3 + 4 = 7"
"foo" * "bar" # "foobar"
'a' # a Char$ = f-string. Bet first: "foo" + "bar"? Concatenation is *."…" text; '…' one character.▶ Script: cell “Strings”.
| Python | Julia | |
|---|---|---|
| First | v[0] |
v[1] |
| Last | v[-1] |
v[end] |
Slice 2:4 |
2, 3 | 2, 3, 4 |
▶ Script: cell “Arrays: 1-based” — try
v[0].
endNo :, no indentation rule.
elseif, one word.c ? a : b= Python’sa if c else b.
let … end: a local scopeLike a function body run at once. Later scripts time code inside
let.
function area_rect(L, w) # 1) long
return L * w
end
square(x) = x^2 # 2) one-line
cube = x -> x^3 # 3) lambda
greet(who; punct = "!") = "Hi $who$punct" # kwarg after ;
greet("Bob"; punct = "?") # "Hi Bob?"return optional: last expression is returned.! (push!, sort!): modifies its argument (convention)..xs = [1.0, 4.0, 9.0]
sqrt.(xs) # [1.0, 2.0, 3.0]
xs .+ 1 # [2.0, 5.0, 10.0]
@. xs^2 + 1 # dot on EVERY opsqrt(xs), without the dot?square.(xs).▶ Script: cell “Broadcasting” — try
sqrt(xs).
struct Point # immutable
x::Float64
y::Float64
end
mutable struct Counter; n::Int; end
pt = Point(1.0, 2.0) # no __init__
c = Counter(0); c.n += 1 # fine
# pt.x = 5.0 # ERRORself: behavior in functions (dispatch module).▶ Script: cell “Structs instead of classes” — try
pt.x = 5.0.
using≈from numpy import *.
▶ Script: cell “Packages”.
Back in every module: timed, then threads, then GPU. ▶ Script: cell “5. Monte-Carlo π”.
| Topic | Python | Julia |
|---|---|---|
| First / last | v[0] / v[-1] |
v[1] / v[end] |
| Slice | v[1:4] excl. 4 |
v[2:4] incl. 4 |
| Blocks / else-if | : + indent / elif |
end / elseif |
| Power / int-div | 2**10 / // |
2^10 / ÷ |
| Concat / f-string | "a"+"b" / f"{x}" |
"a"*"b" / "$x" |
| Element-wise | np.f(x) |
f.(x) |
| Method call | obj.method() |
method(obj) |
| Class | class C + self |
struct C |
| Copy vs alias | b = a[:] copies |
b = a aliases; copy(a) |
| Absent value | None |
nothing / missing |
end, element-wise is the dot, behavior lives in functions.⬅ Previous: Overview · Next: 1 — Interpreted vs compiled ➡