Skip to content

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

变量

变量赋值

支持 Unicode 变量名

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

数组

创建数组

数组按列主序存储

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

宏卫生

宏卫生避免变量冲突

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,其中 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

这篇内容对您有帮助吗?