基礎
Hello World
println は改行を追加し、print は改行しません
println("Hello, World!")
print("No newline")コメント
#= =# で複数行コメントを書きます
# Single-line comment
#=
Multi-line
comment
=#
# Docstring
"""docstring"""REPL
ans に直前の結果が格納されます
$ julia
julia> 1 + 1
2
julia> ans # previous result
2文字列補間
変数は $、式は $(expression) で埋め込みます
name = "Alice"
age = 30
println("$name is $age")
println("$(age * 2)")連鎖比較
Julia は連鎖比較をサポートしています
x = 5
1 < x < 10 # true
1 <= x <= 10 # true変数
変数の代入
Unicode の変数名も使えます
x = 10
name = "Alice"
π = 3.14159 # supports Unicode
δ = 0.001定数
const でグローバル定数を宣言します
const PI = 3.14159
const MAX_SIZE = 100
# const declares a constant型アノテーション
型アノテーションには :: を使います
x::Int = 10
y::Float64 = 3.14
function f(x::Int)::String
string(x)
end多重代入
多重代入をサポートしています
a, b, c = 1, 2, 3
x, y = y, x # swap
(a, b) = (1, 2)型
基本の型
typeof で型を取得します
typeof(42) # Int64
typeof(3.14) # Float64
typeof("hi") # String
typeof(true) # Bool
typeof('a') # Char型変換
型名を変換関数として使います
Int(3.14) # 3
Float64(3) # 3.0
String(42) # "42"
Char(65) # 'A'抽象型
abstract type で抽象型を定義します
abstract type Animal end
abstract type Dog <: Animal end
# <: denotes subtype relationship構造体
struct は不変(イミュータブル)です
struct Point
x::Float64
y::Float64
end
p = Point(1.0, 2.0)
p.x # 1.0可変構造体
mutable struct はフィールドの変更を許します
mutable struct Counter
count::Int
end
c = Counter(0)
c.count += 1パラメトリック型
T は型パラメータです
struct Point{T}
x::T
y::T
end
p = Point{Float64}(1.0, 2.0)
q = Point{Int}(1, 2)多重ディスパッチ
関数のオーバーロード
Julia の中核機能: 多重ディスパッチ
function describe(x::Int)
"integer: $x"
end
function describe(x::String)
"string: $x"
end
describe(42) # "integer: 42"
describe("hi") # "string: hi"パラメトリックメソッド
where で型パラメータを指定します
function norm(p::Point{T}) where T
sqrt(p.x^2 + p.y^2)
end
# Works for all types Tフォールバックメソッド
型アノテーションなしのメソッドはデフォルトとして動作します
function describe(x)
"unknown: $x"
end
# No type annotation, matches all argumentsメソッドの曖昧性
メソッドの曖昧さを避けるように注意しましょう
f(x::Int, y) = 1
f(x, y::Int) = 2
# f(1, 1) raises an ambiguity error
# Need to define f(x::Int, y::Int) = 3関数
関数の定義
return は省略可能で、最後の式の値が返ります
function add(a, b)
return a + b
end
# Shorthand
add(a, b) = a + b無名関数
-> で無名関数を定義します
f = x -> x^2
f(5) # 25
map(x -> x * 2, [1, 2, 3])複数の戻り値
複数の値はタプルとして返します
function divrem2(a, b)
return a ÷ b, a % b
end
q, r = divrem2(10, 3)キーワード引数
; 以降はキーワード引数になります
function plot(x, y; style="line", color="blue")
# style and color are keyword arguments
end
plot(1:10, 1:10, color="red")可変長引数
... で可変長の引数をまとめます
function sumall(args...)
sum(args)
end
sumall(1, 2, 3, 4) # 10do ブロック
do ブロックは無名関数を渡します
map([1, 2, 3]) do x
x ^ 2
end
# Equivalent to map(x -> x^2, [1,2,3])制御フロー
if-elseif-else
条件分岐の構文です
if x > 0
println("positive")
elseif x < 0
println("negative")
else
println("zero")
end三項演算子
condition ? true_value : false_value の形式で条件式を書きます
result = x > 0 ? "pos" : "neg"
# Chained
result = x > 0 ? "pos" : x < 0 ? "neg" : "zero"for ループ
for in で繰り返します
for i in 1:5
println(i)
end
for (i, v) in enumerate(arr)
println(i, v)
endwhile ループ
while によるループです
i = 1
while i <= 5
println(i)
i += 1
endbreak と continue
条件には && の短絡評価も使えます
for i in 1:10
i == 5 && break
i % 2 == 0 && continue
println(i)
end配列
配列の作成
配列は列優先(column-major)です
a = [1, 2, 3, 4, 5]
b = [1 2 3; 4 5 6] # 2x3 matrix
c = zeros(3, 3)
d = ones(5)
e = rand(2, 2)配列のインデックス
インデックスは 1 から始まります
a = [10, 20, 30, 40, 50]
a[1] # 10 (1-based)
a[end] # 50
a[2:4] # [20, 30, 40]
a[[1, 3]] # [10, 30]配列の操作
末尾の ! は破壊的な変更を意味します
push!(a, 60) # add to end
pop!(a) # remove from end
append!(a, b) # concatenate
sort(a) # sort (returns new array)
sort!(a) # in-place sort配列内包表記
リスト内包表記に似ています
[x^2 for x in 1:5]
# [1, 4, 9, 16, 25]
[x^2 for x in 1:10 if x % 2 == 0]
# [4, 16, 36, 64, 100]ブロードキャスト
ブロードキャストには . 演算子を使います
a = [1, 2, 3]
a .^ 2 # [1, 4, 9]
f.(a) # apply f to each element
a .+ 10 # [11, 12, 13]タプル
タプル
タプルは不変です
t = (1, 2, 3)
t[1] # 1
t[2] # 2
# Named tuple
nt = (name="Alice", age=30)
nt.name # "Alice"分割代入
タプルの分割代入ができます
a, b, c = (1, 2, 3)
(first, second) = (10, 20)
# Ignore
_, y = (1, 2)辞書
辞書の作成
Dict で辞書を作ります
d = Dict("a" => 1, "b" => 2)
d2 = Dict(:name => "Alice", :age => 30)
d["c"] = 3 # addアクセスと変更
アクセスも変更も [] で行います
d = Dict("a" => 1, "b" => 2)
d["a"] # 1
d["a"] = 10 # modify
delete!(d, "b") # delete反復処理
キーと値のペアを反復します
for (k, v) in d
println(k, " => ", v)
end
keys(d) # all keys
values(d) # all values辞書の操作
よく使う辞書の関数
haskey(d, "a") # true
get(d, "x", 0) # default value 0
get!(d, "x", 0) # add if missing
merge(d1, d2) # merge文字列
文字列の基本
文字列のインデックスは連続しないことがあります(UTF-8)
s = "Hello World"
length(s) # 11
s[1] # 'H'
s[1:5] # "Hello"
lastindex(s) # 11文字列の操作
よく使う文字列の関数
uppercase("hi") # "HI"
lowercase("HI") # "hi"
reverse("hello") # "olleh"
strip(" hi ") # "hi"検索と置換
文字列の検索と置換
s = "Hello World"
findfirst("World", s) # 7:11
occursin("World", s) # true
replace(s, "World" => "Julia") # "Hello Julia"分割と結合
split と join
split("a,b,c", ",") # ["a", "b", "c"]
join(["a", "b"], "-") # "a-b"
split("hello", "") # ['h','e','l','l','o']数学関数
基本の数学関数
組み込みの数学関数
abs(-5) # 5
sqrt(16) # 4.0
cbrt(27) # 3.0
sign(-5) # -1
floor(3.7) # 3.0
ceil(3.2) # 4.0三角関数
角度はラジアンで指定します
sin(π/2) # 1.0
cos(0) # 1.0
tan(π/4) # 1.0
asin(1) # 1.5707... (π/2)対数と指数
log は自然対数です
log(ℯ) # 1.0 (natural log)
log2(8) # 3.0
log10(100) # 2.0
exp(1) # 2.718... (ℯ)特殊な値
数学定数と特殊な値
π # 3.14159...
ℯ # 2.71828...
Inf # positive infinity
NaN # not a number
im # imaginary unit線形代数
行列の操作
LinearAlgebra 標準ライブラリを使います
using LinearAlgebra
A = [1 2; 3 4]
A' # transpose
inv(A) # inverse matrix
det(A) # determinant
rank(A) # rank行列の分解
さまざまな行列分解
A = [1.0 2.0; 3.0 4.0]
F = lu(A) # LU decomposition
F = qr(A) # QR decomposition
F = svd(A) # SVD decomposition
F = eigen(A) # eigendecompositionベクトルの操作
ベクトルの操作
v1 = [1, 2, 3]
v2 = [4, 5, 6]
dot(v1, v2) # dot product
cross(v1, v2) # cross product
norm(v1) # norm
v1 ⋅ v2 # dot product (Unicode)統計
基本の統計
Statistics 標準ライブラリ
using Statistics
data = [1, 2, 3, 4, 5]
mean(data) # 3.0
median(data) # 3.0
std(data) # standard deviation
var(data) # variance分位数
分位数の計算
using Statistics
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
quantile(data, 0.25) # 3.25
quantile(data, 0.5) # 5.5
quantile(data, 0.75) # 7.75相関と共分散
相関係数と共分散
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
cor(x, y) # 1.0 (correlation coefficient)
cov(x, y) # covarianceプロット
基本のプロット
Plots.jl が主要なプロットライブラリです
using Plots
x = 1:10
y = x .^ 2
plot(x, y, title="Quadratic", label="x^2")散布図
scatter で散布図を描きます
using Plots
x = rand(50)
y = rand(50)
scatter(x, y, markersize=5, color=:red)サブプロット
layout でサブプロットの配置を制御します
using Plots
p1 = plot(1:10, 1:10)
p2 = plot(1:10, (1:10).^2)
plot(p1, p2, layout=(2, 1))画像の保存
savefig で画像を保存します
using Plots
p = plot(sin, 0, 2π)
savefig(p, "sine.png")DataFrames
DataFrame の作成
DataFrames.jl は pandas に似ています
using DataFrames
df = DataFrame(
name = ["Alice", "Bob", "Carol"],
age = [25, 30, 35],
city = ["NYC", "LA", "SF"]
)データへのアクセス
行と列へのアクセス
df.name # column
df[1, :] # first row
df[:, :age] # age column
df[1:2, :] # first two rowsフィルタとソート
フィルタリングとソート
using DataFrames
filter(:age => >(28), df) # age > 28
sort(df, :age) # sort by age
sort(df, :age, rev=true) # descendingグループ化と集計
グループ化した集計には groupby + combine を使います
using DataFrames, Statistics
combine(groupby(df, :city), :age => mean => :avg_age)ファイル I/O
テキストの読み書き
open の do ブロックはファイルを自動的に閉じます
# Write
open("output.txt", "w") do f
write(f, "Hello World")
end
# Read
content = read("input.txt", String)1 行ずつの読み込み
eachline で 1 行ずつ反復します
for line in eachline("data.txt")
println(line)
end
# Or
lines = readlines("data.txt")CSV ファイル
CSV.jl で CSV ファイルを扱います
using CSV, DataFrames
df = CSV.read("data.csv", DataFrame)
CSV.write("output.csv", df)JSON ファイル
JSON.jl で JSON を扱います
using JSON
data = JSON.parsefile("data.json")
JSON.print("output.json", data)モジュール
モジュールの定義
export で公開インターフェースを宣言します
module MyModule
export greet, add
greet(name) = println("Hello $name")
add(a, b) = a + b
end # moduleモジュールのインポート
using と import の違い
using MyModule # imports exported names
using MyModule: greet # selective import
import MyModule # needs MyModule.greet
import MyModule: add # selective import標準モジュール
標準ライブラリのモジュール
using Dates # date and time
using LinearAlgebra # linear algebra
using Statistics # statistics
using Random # random numbersマクロ
マクロの定義
マクロはコンパイル時に AST を操作します
macro sayhi(name)
return :(println("Hi, $name"))
end
@sayhi "Alice" # Hi, Alice式のクォート
:() で式オブジェクトを作ります
ex = :(1 + 2)
# :(1 + 2)
dump(ex)
# Expr
# head: Symbol call
# args: Array[...]よく使うマクロ
組み込みの常用マクロ
@time sleep(1) # timing
@assert 1 == 1 # assertion
@show x # print variable name and value
@elapsed sleep(0.1) # return only time
@which sin(1) # view method locationメタプログラミング
式の構築
Expr で AST を構築します
ex = Expr(:call, :+, 1, 2)
eval(ex) # 3
# Equivalent to
eval(:(1 + 2)) # 3コード生成
ループでコードを生成します
for op in (:+, :-, :*, :/)
eval(:(f($op, a, b) = $op(a, b)))
end
f(+, 1, 2) # 3マクロの衛生性
マクロの衛生性により変数名の衝突を避けられます
macro setx(val)
return :(x = $val)
end
# Variables in macros are hygienic and won't pollute the caller's scope並列コンピューティング
マルチスレッド
並列ループには @threads マクロを使います
# Start: julia --threads=4
Threads.nthreads() # 4
Threads.@threads for i in 1:100
results[i] = compute(i)
end分散コンピューティング
Distributed 標準ライブラリ
using Distributed
addprocs(4) # add 4 worker processes
@everywhere function work(x)
x ^ 2
end
pmap(work, 1:100) # parallel mapリモート呼び出し
非同期のリモート呼び出し
using Distributed
ref = @spawnat :any sqrt(16)
fetch(ref) # 4.0
# @spawnat executes on a specified processコルーチン
Task
Task は Julia のコルーチンです
t = Task(() -> begin
println("running")
return 42
end)
schedule(t)
wait(t)Channel
コルーチン間の通信には Channel を使います
ch = Channel(32)
put!(ch, 1)
put!(ch, 2)
take!(ch) # 1
take!(ch) # 2プロデューサー・コンシューマー
コルーチンでプロデューサー・コンシューマーを実装します
function producer(ch)
for i in 1:5
put!(ch, i)
end
end
task = @task producer(Channel(10))
for val in task
println(val)
end例外処理
try-catch
try-catch-finally の構造で例外を処理します
try
risky()
catch e
println("Error: $e")
finally
cleanup()
end例外のスロー
throw で例外オブジェクトを投げます
throw(ErrorException("something wrong"))
throw(DomainError(-1, "negative"))
error("generic error")カスタム例外
Exception 型を継承します
struct MyError <: Exception
msg::String
end
throw(MyError("custom error"))アサーション
@assert マクロ
@assert x > 0 "x must be positive"
# Throws AssertionError when condition is false正規表現
正規表現
r"" で正規表現を作ります
re = r"\d+"
occursin(re, "abc123") # true
match(re, "abc123") # RegexMatchマッチ
match はマッチ結果を返します