julia> struct Dog end; struct Cat end
julia> meet(a::Dog, b::Dog) = "The dogs play together"
meet(a::Dog, b::Cat) = "The dog chases the cat"
meet(a::Cat, b::Dog) = "The cat hisses at the dog"
meet(a::Cat, b::Cat) = "The cats ignore each other"
julia> meet(Dog(), Cat())
"The dog chases the cat"
julia> meet(Cat(), Dog())
"The cat hisses at the dog"
julia> struct Nutshell{T}
contents::T
end
julia> Base.show(io::IO, n::Nutshell) = print(io, "🥜 ", n.contents, " 🥜")
julia> Nutshell("Julia")
🥜 Julia 🥜
julia> α, β = 0.5, 0.3
julia> f(x) = α*x + β
julia> ∑(v) = reduce(+, v)
julia> ∑(f.(1:5))
9.0
julia> [x^2 for x in 1:5]
5-element Vector{Int64}:
1
4
9
16
25
julia> Dict(c => i for (i,c) in enumerate("julia"))
Dict{Char, Int64} with 5 entries:
'u' => 2
'a' => 5
'i' => 4
'j' => 1
'l' => 3
julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
1 2
3 4
julia> sin.(A) .+ 1
2×2 Matrix{Float64}:
1.84147 1.9093
1.14112 0.243198
julia> 1:5 |> sum |> sqrt
3.872983346207417
julia> (sqrt ∘ sum)(1:5)
3.872983346207417
julia> map(exp ∘ abs, [-1, 2, -3])
[2.718, 7.389, 20.086]
julia> (a, b, c) = 1:3
julia> a, c
(1, 3)
julia> head, tail... = ["first", "second", "third"]
julia> head, tail
("first", ["second", "third"])
julia> ex = :(1 + 2 * 3)
:(1 + 2 * 3)
julia> typeof(ex)
Expr
julia> eval(ex)
7
julia> using DataFrames
│ Package DataFrames not found, but a package named DataFrames is available from a registry.
│ Install package?
│ (myproject) pkg> add DataFrames
â”” (y/n/o) [y]: y
julia> df = DataFrame(name=["Alice", "Bob"], age=[25, 30])
2×2 DataFrame
Row │ name age
│ String Int64
─────┼───────────────
1 │ Alice 25
2 │ Bob 30
julia> function greet(name, greeting="Hello"; punctuation="!")
"$greeting, $name$punctuation"
end
julia> greet("Julia")
"Hello, Julia!"
julia> greet("world", "Hi"; punctuation=".")
"Hi, world."
julia> function fib(n)
n < 2 && return n
t = Threads.@spawn fib(n - 2)
return fib(n - 1) + fetch(t)
end
julia> fib(10)
55
julia> Threads.nthreads()
8
julia> # Press ] for package mode
(@v{{stable_release_short}}) pkg> status
Status `~/.julia/environments/v{{stable_release_short}}/Project.toml`
[6e4b80f9] BenchmarkTools v1.5.0
julia> # Press ; for shell mode
shell> ls *.jl
main.jl test.jl utils.jl
julia> # Press ? for help mode
help?> sum
sum(f, itr) – Sum the results of calling f on each element of itr.
julia> f(x, y) = x + y
julia> @code_warntype f(1, 2)
MethodInstance for f(::Int64, ::Int64)
Arguments
x::Int64
y::Int64
Body::Int64
│ %1 = (x + y)::Int64
└── return %1
julia> @code_llvm f(1, 2)
define i64 @julia_f(...) {
%0 = add i64 %"y::Int64", %"x::Int64"
ret i64 %0
}
julia> @code_native f(1, 2)
add x0, x1, x0
ret