기본
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변수
변수 할당
유니코드 변수 이름을 지원합니다
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)파일 입출력
텍스트 읽고 쓰기
open do 블록이 파일을 자동으로 닫습니다
# Write
open("output.txt", "w") do f
write(f, "Hello World")
end
# Read
content = read("input.txt", String)한 줄씩 읽기
eachline이 줄 단위로 순회합니다