Skip to content

Julia 치트시트

Julia는 기술 컴퓨팅을 위한 고수준 고성능 동적 언어입니다.

01

기본

Hello World 출력

println은 개행을 더하고, print는 더하지 않습니다

julia
println("Hello, World!")
print("No newline")

주석

여러 줄 주석에는 #= =#을 씁니다

julia
# Single-line comment

#=
  Multi-line
  comment
=#

# Docstring
"""docstring"""

REPL(대화형 실행 환경)

ans에 이전 결과가 저장됩니다

julia
$ julia
julia> 1 + 1
2
julia> ans  # previous result
2

문자열 보간

변수에는 $, 표현식에는 $(expression)을 씁니다

julia
name = "Alice"
age = 30
println("$name is $age")
println("$(age * 2)")

연쇄 비교

Julia는 연쇄 비교를 지원합니다

julia
x = 5
1 < x < 10  # true
1 <= x <= 10  # true
02

변수

변수 할당

유니코드 변수 이름을 지원합니다

julia
x = 10
name = "Alice"
π = 3.14159  # supports Unicode
δ = 0.001

상수

const가 전역 상수를 선언합니다

julia
const PI = 3.14159
const MAX_SIZE = 100
# const declares a constant

타입 어노테이션

타입 어노테이션에는 ::을 씁니다

julia
x::Int = 10
y::Float64 = 3.14
function f(x::Int)::String
  string(x)
end

다중 할당

다중 할당을 지원합니다

julia
a, b, c = 1, 2, 3
x, y = y, x  # swap
(a, b) = (1, 2)
03

타입

기본 타입

typeof가 타입을 얻습니다

julia
typeof(42)       # Int64
typeof(3.14)     # Float64
typeof("hi")     # String
typeof(true)     # Bool
typeof('a')      # Char

타입 변환

타입 이름을 변환 함수처럼 씁니다

julia
Int(3.14)    # 3
Float64(3)   # 3.0
String(42)   # "42"
Char(65)     # 'A'

추상 타입

abstract type이 추상 타입을 정의합니다

julia
abstract type Animal end
abstract type Dog <: Animal end
# <: denotes subtype relationship

구조체

struct는 불변입니다

julia
struct Point
  x::Float64
  y::Float64
end

p = Point(1.0, 2.0)
p.x  # 1.0

가변 구조체

mutable struct는 필드 수정을 허용합니다

julia
mutable struct Counter
  count::Int
end

c = Counter(0)
c.count += 1

파라미터화 타입

T가 타입 매개변수입니다

julia
struct Point{T}
  x::T
  y::T
end

p = Point{Float64}(1.0, 2.0)
q = Point{Int}(1, 2)
04

다중 디스패치

함수 오버로딩

Julia의 핵심 기능: 다중 디스패치

julia
function describe(x::Int)
  "integer: $x"
end

function describe(x::String)
  "string: $x"
end

describe(42)      # "integer: 42"
describe("hi")    # "string: hi"

파라미터화 메서드

where가 타입 매개변수를 지정합니다

julia
function norm(p::Point{T}) where T
  sqrt(p.x^2 + p.y^2)
end

# Works for all types T

폴백 메서드

타입 어노테이션이 없는 메서드가 기본 역할을 합니다

julia
function describe(x)
  "unknown: $x"
end

# No type annotation, matches all arguments

메서드 모호성

메서드 모호성을 피하도록 주의하세요

julia
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
05

함수

함수 정의

return은 선택 사항이며 마지막 표현식을 반환합니다

julia
function add(a, b)
  return a + b
end

# Shorthand
add(a, b) = a + b

익명 함수

->가 익명 함수를 정의합니다

julia
f = x -> x^2
f(5)  # 25

map(x -> x * 2, [1, 2, 3])

다중 반환 값

여러 값을 반환할 때는 튜플을 반환합니다

julia
function divrem2(a, b)
  return a ÷ b, a % b
end

q, r = divrem2(10, 3)

키워드 인수

; 뒤가 키워드 인수입니다

julia
function plot(x, y; style="line", color="blue")
  # style and color are keyword arguments
end

plot(1:10, 1:10, color="red")

가변 인수

...이 가변 인수를 수집합니다

julia
function sumall(args...)
  sum(args)
end

sumall(1, 2, 3, 4)  # 10

do 블록

do 블록이 익명 함수를 전달합니다

julia
map([1, 2, 3]) do x
  x ^ 2
end
# Equivalent to map(x -> x^2, [1,2,3])
06

제어 흐름

if-elseif-else 조건문

조건 표현식입니다

julia
if x > 0
  println("positive")
elseif x < 0
  println("negative")
else
  println("zero")
end

삼항 연산자

condition ? true_value : false_value

julia
result = x > 0 ? "pos" : "neg"

# Chained
result = x > 0 ? "pos" : x < 0 ? "neg" : "zero"

for 루프

for in으로 순회합니다

julia
for i in 1:5
  println(i)
end

for (i, v) in enumerate(arr)
  println(i, v)
end

while 루프

while 루프입니다

julia
i = 1
while i <= 5
  println(i)
  i += 1
end

break와 continue

&&가 조건용 단락 평가를 합니다

julia
for i in 1:10
  i == 5 && break
  i % 2 == 0 && continue
  println(i)
end
07

배열

배열 생성

배열은 column-major입니다

julia
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부터 시작합니다

julia
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]

배열 연산

! 접미사는 제자리 수정을 의미합니다

julia
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

배열 컴프리헨션

리스트 컴프리헨션과 비슷합니다

julia
[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]

브로드캐스팅

브로드캐스팅에는 . 연산자를 씁니다

julia
a = [1, 2, 3]
a .^ 2       # [1, 4, 9]
f.(a)        # apply f to each element
a .+ 10      # [11, 12, 13]
08

튜플

튜플

튜플은 불변입니다

julia
t = (1, 2, 3)
t[1]  # 1
t[2]  # 2

# Named tuple
nt = (name="Alice", age=30)
nt.name  # "Alice"

구조 분해

튜플 구조 분해 할당입니다

julia
a, b, c = (1, 2, 3)
(first, second) = (10, 20)

# Ignore
_, y = (1, 2)
09

딕셔너리

딕셔너리 생성

Dict가 딕셔너리를 만듭니다

julia
d = Dict("a" => 1, "b" => 2)
d2 = Dict(:name => "Alice", :age => 30)
d["c"] = 3  # add

접근과 수정

접근과 수정에는 []을 씁니다

julia
d = Dict("a" => 1, "b" => 2)
d["a"]      # 1
d["a"] = 10 # modify
delete!(d, "b")  # delete

순회

키-값 쌍을 순회합니다

julia
for (k, v) in d
  println(k, " => ", v)
end

keys(d)    # all keys
values(d)  # all values

딕셔너리 연산

흔한 딕셔너리 함수들입니다

julia
haskey(d, "a")    # true
get(d, "x", 0)     # default value 0
get!(d, "x", 0)    # add if missing
merge(d1, d2)      # merge
10

문자열

문자열 기본

문자열 인덱스는 연속적이지 않을 수 있습니다(UTF-8)

julia
s = "Hello World"
length(s)    # 11
s[1]         # 'H'
s[1:5]       # "Hello"
lastindex(s) # 11

문자열 연산

흔한 문자열 함수들입니다

julia
uppercase("hi")    # "HI"
lowercase("HI")    # "hi"
reverse("hello")   # "olleh"
strip("  hi  ")     # "hi"

찾기와 바꾸기

찾기와 바꾸기입니다

julia
s = "Hello World"
findfirst("World", s)  # 7:11
occursin("World", s)   # true
replace(s, "World" => "Julia")  # "Hello Julia"

분할과 결합

split과 join입니다

julia
split("a,b,c", ",")   # ["a", "b", "c"]
join(["a", "b"], "-")  # "a-b"
split("hello", "")     # ['h','e','l','l','o']
11

수학 함수

기본 수학

내장 수학 함수들입니다

julia
abs(-5)      # 5
sqrt(16)    # 4.0
cbrt(27)    # 3.0
sign(-5)    # -1
floor(3.7)  # 3.0
ceil(3.2)   # 4.0

삼각 함수

라디안 단위입니다

julia
sin(π/2)   # 1.0
cos(0)     # 1.0
tan(π/4)  # 1.0
asin(1)   # 1.5707... (π/2)

로그와 지수

log는 자연로그입니다

julia
log(ℯ)      # 1.0 (natural log)
log2(8)    # 3.0
log10(100) # 2.0
exp(1)     # 2.718... (ℯ)

특수 값

수학 상수와 특수 값입니다

julia
π     # 3.14159...
ℯ     # 2.71828...
Inf   # positive infinity
NaN   # not a number
im    # imaginary unit
12

선형대수

행렬 연산

LinearAlgebra 표준 라이브러리입니다

julia
using LinearAlgebra

A = [1 2; 3 4]
A'        # transpose
inv(A)    # inverse matrix
det(A)    # determinant
rank(A)   # rank

행렬 분해

다양한 행렬 분해입니다

julia
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

벡터 연산

벡터 연산입니다

julia
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)
13

통계

기본 통계

Statistics 표준 라이브러리입니다

julia
using Statistics

data = [1, 2, 3, 4, 5]
mean(data)    # 3.0
median(data)  # 3.0
std(data)     # standard deviation
var(data)     # variance

분위수

분위수 계산입니다

julia
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

상관과 공분산

상관계수와 공분산입니다

julia
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
cor(x, y)    # 1.0 (correlation coefficient)
cov(x, y)    # covariance
14

플로팅

기본 플로팅

Plots.jl이 주요 플로팅 라이브러리입니다

julia
using Plots

x = 1:10
y = x .^ 2
plot(x, y, title="Quadratic", label="x^2")

산점도

scatter가 산점도를 그립니다

julia
using Plots

x = rand(50)
y = rand(50)
scatter(x, y, markersize=5, color=:red)

서브플롯

layout이 서브플롯 레이아웃을 제어합니다

julia
using Plots

p1 = plot(1:10, 1:10)
p2 = plot(1:10, (1:10).^2)
plot(p1, p2, layout=(2, 1))

이미지 저장

savefig가 이미지를 저장합니다

julia
using Plots

p = plot(sin, 0, 2π)
savefig(p, "sine.png")
15

DataFrames 패키지

DataFrame 생성

DataFrames.jl은 pandas와 비슷합니다

julia
using DataFrames

df = DataFrame(
  name = ["Alice", "Bob", "Carol"],
  age = [25, 30, 35],
  city = ["NYC", "LA", "SF"]
)

데이터 접근

행과 열 접근입니다

julia
df.name      # column
df[1, :]     # first row
df[:, :age]  # age column
df[1:2, :]   # first two rows

필터와 정렬

필터링과 정렬입니다

julia
using DataFrames

filter(:age => >(28), df)  # age > 28
sort(df, :age)            # sort by age
sort(df, :age, rev=true)  # descending

그룹과 집계

그룹화된 집계에는 groupby + combine을 씁니다

julia
using DataFrames, Statistics

combine(groupby(df, :city), :age => mean => :avg_age)
16

파일 입출력

텍스트 읽고 쓰기

open do 블록이 파일을 자동으로 닫습니다

julia
# Write
open("output.txt", "w") do f
  write(f, "Hello World")
end

# Read
content = read("input.txt", String)

한 줄씩 읽기

eachline이 줄 단위로 순회합니다

julia
for line in eachline("data.txt")
  println(line)
end

# Or
lines = readlines("data.txt")

CSV 파일

CSV.jl이 CSV 파일을 다룹니다

julia
using CSV, DataFrames

df = CSV.read("data.csv", DataFrame)
CSV.write("output.csv", df)

JSON 파일

JSON.jl이 JSON을 다룹니다

julia
using JSON

data = JSON.parsefile("data.json")
JSON.print("output.json", data)
17

모듈

모듈 정의

export가 공개 인터페이스를 선언합니다

julia
module MyModule

export greet, add

greet(name) = println("Hello $name")
add(a, b) = a + b

end  # module

모듈 임포트

using과 import의 차이입니다

julia
using MyModule     # imports exported names
using MyModule: greet  # selective import
import MyModule        # needs MyModule.greet
import MyModule: add    # selective import

표준 모듈

표준 라이브러리 모듈들입니다

julia
using Dates        # date and time
using LinearAlgebra # linear algebra
using Statistics     # statistics
using Random         # random numbers
18

매크로

매크로 정의

매크로는 컴파일 타임에 AST를 다룹니다

julia
macro sayhi(name)
  return :(println("Hi, $name"))
end

@sayhi "Alice"  # Hi, Alice

표현식 쿼팅

:()가 표현식 객체를 만듭니다

julia
ex = :(1 + 2)
# :(1 + 2)

dump(ex)
# Expr
#   head: Symbol call
#   args: Array[...]

흔한 매크로

내장 흔한 매크로들입니다

julia
@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
19

메타프로그래밍

표현식 구성

Expr이 AST를 구성합니다

julia
ex = Expr(:call, :+, 1, 2)
eval(ex)  # 3

# Equivalent to
eval(:(1 + 2))  # 3

코드 생성

코드를 생성하기 위한 루프입니다

julia
for op in (:+, :-, :*, :/)
  eval(:(f($op, a, b) = $op(a, b)))
end

f(+, 1, 2)  # 3

매크로 위생

매크로 위생(hygiene)이 변수 충돌을 피합니다

julia
macro setx(val)
  return :(x = $val)
end

# Variables in macros are hygienic and won't pollute the caller's scope
20

병렬 컴퓨팅

멀티스레딩

병렬 루프에는 @threads 매크로를 씁니다

julia
# Start: julia --threads=4
Threads.nthreads()  # 4

Threads.@threads for i in 1:100
  results[i] = compute(i)
end

분산 컴퓨팅

Distributed 표준 라이브러리입니다

julia
using Distributed
addprocs(4)  # add 4 worker processes

@everywhere function work(x)
  x ^ 2
end

pmap(work, 1:100)  # parallel map

원격 호출

비동기 원격 호출입니다

julia
using Distributed

ref = @spawnat :any sqrt(16)
fetch(ref)  # 4.0

# @spawnat executes on a specified process
21

코루틴

Task(코루틴)

Task가 Julia의 코루틴입니다

julia
t = Task(() -> begin
  println("running")
  return 42
end)

schedule(t)
wait(t)

Channel(채널)

코루틴 간 통신에는 Channel을 씁니다

julia
ch = Channel(32)

put!(ch, 1)
put!(ch, 2)
take!(ch)  # 1
take!(ch)  # 2

생산자-소비자

코루틴으로 생산자-소비자를 구현합니다

julia
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
22

예외 처리

try-catch 예외 처리

try-catch-finally입니다

julia
try
  risky()
catch e
  println("Error: $e")
finally
  cleanup()
end

예외 던지기

throw가 예외 객체를 발생시킵니다

julia
throw(ErrorException("something wrong"))
throw(DomainError(-1, "negative"))
error("generic error")

커스텀 예외

Exception 타입을 상속하세요

julia
struct MyError <: Exception
  msg::String
end

throw(MyError("custom error"))

어설션

@assert 매크로입니다

julia
@assert x > 0 "x must be positive"
# Throws AssertionError when condition is false
23

정규식

정규 표현식

r""가 정규식을 만듭니다

julia
re = r"\d+"
occursin(re, "abc123")  # true
match(re, "abc123")     # RegexMatch

매치

match가 매칭 결과를 반환합니다

julia
m = match(r"(\w+)@(\w+)", "user@host")
m.match   # "user@host"
m.captures  # ["user", "host"]
m[1]      # "user"

전체 찾기

eachmatch가 모든 매칭을 순회합니다

julia
for m in eachmatch(r"\d+", "a1b2c3")
  println(m.match)
end
# 1, 2, 3

교체

replace가 정규식을 지원합니다

julia
replace("a1b2c3", r"\d" => "#")
# "a#b#c#"

replace("hello", r"l" => "L" => count=1)
# "heLlo"
24

DateTime(날짜와 시간)

날짜 생성

Dates 표준 라이브러리입니다

julia
using Dates

now()                    # current time
Date(2024, 1, 15)       # date
DateTime(2024, 1, 15, 10, 30)  # datetime

포매팅

포매팅과 파싱입니다

julia
using Dates

dt = now()
Dates.format(dt, "yyyy-mm-dd HH:MM:SS")
Date("2024-01-15", "yyyy-mm-dd")

날짜 연산

시간 간격 타입입니다

julia
using Dates

d1 = Date(2024, 1, 1)
d2 = d1 + Day(30)     # add 30 days
diff = d2 - d1        # 30 days
Day(1) + Hour(12)     # datetime arithmetic
25

패키지

패키지 설치

Pkg.add가 패키지를 설치합니다

julia
using Pkg
Pkg.add("Plots")
Pkg.add(["DataFrames", "CSV"])
Pkg.rm("Plots")  # remove

패키지 관리

흔한 Pkg 커맨드들입니다

julia
Pkg.status()    # view installed
Pkg.update()    # update all
Pkg.instantiate()  # install per Project.toml
Pkg.activate("env")  # activate environment

환경

프로젝트 환경 관리입니다

julia
# Project.toml defines dependencies
# Manifest.toml locks versions

Pkg.activate("myproject")  # activate environment
Pkg.resolve()  # resolve dependencies
26

Pkg 매니저

REPL Pkg 모드

]가 Pkg REPL 모드로 진입합니다

julia
julia> ]
pkg> add Plots
pkg> rm Plots
pkg> status
pkg> update
pkg> test Plots

패키지 생성

generate가 패키지 골격을 만듭니다

julia
pkg> generate MyPackage

# Directory structure
# MyPackage/
#   Project.toml
#   src/MyPackage.jl

개발 모드

dev가 개발 모드로 설치합니다

julia
pkg> dev ./MyPackage  # local development
pkg> dev MyPackage    # dev version from GitHub
pkg> free MyPackage   # exit development mode
27

상호운용성

C 호출

ccall이 C 함수를 호출합니다

julia
ccall((:sqrt, "libm"), Float64, (Float64,), 16.0)
# 4.0

Python 호출

PyCall.jl이 Python을 호출합니다

julia
using PyCall
np = pyimport("numpy")
np.array([1, 2, 3])
np.mean([1, 2, 3])

R 호출

RCall.jl이 R을 호출합니다

julia
using RCall
R"sd(c(1,2,3,4,5))"  # call R code
28

GPU 컴퓨팅

CUDA 배열

CUDA.jl이 NVIDIA GPU를 지원합니다

julia
using CUDA

a = CUDA.ones(1000)
b = CUDA.zeros(1000)
c = a .+ b  # operations on GPU

GPU 커널

@cuda가 GPU 커널을 실행합니다

julia
using CUDA

function kernel!(a)
  i = threadIdx().x
  if i <= length(a)
    @inbounds a[i] *= 2
  end
  return
end

@cuda threads=256 kernel!(a)

AMD GPU 가속

AMDGPU.jl이 AMD GPU를 지원합니다

julia
using AMDGPU

a = ROCArray(ones(100))
b = a .* 2  # operations on AMD GPU

Was this helpful?