Julia 函数
用采样数据理解函数调用、派发、关键字参数、组合以及 do 块的资源管理。
学完这一章,你能够
- 用采样数据理解函数调用、派发、关键字参数、组合以及 do 块的资源管理。
定义、派发和结果
用 function 与 end 定义方法,简短定义可写 f(x)=表达式。默认返回最后求值的表达式,也可用 return 提前结束。不带括号的 f 表示函数对象,可用其它变量引用,Unicode 标识符也可用作函数名。
参数后写 ::Integer 会限制该方法适用的类型。没有匹配方法时会报 MethodError。是否写具体类型主要由接口和派发需要决定,常规调用仍会按实际输入类型特化。函数签名的返回类型注解会转换返回值,不能表示时可能报 InexactError。
需要返回几项值时可以组成元组,调用方再解构。只做副作用的函数可明确返回 nothing。
位置参数、选项和展开
最后几个位置参数可有默认值,相当于提供对应参数个数的方法。关键字参数通常放在分号后,调用也可在参数列表中用逗号写出 name=value。在本站验证的 Julia 1.10.13 中,逗号形式的关键字写在位置参数之前也能调用。书写时把关键字放到分号后,参数角色更清楚。
kwargs... 收集未匹配的关键字,实际对象为 Base.Pairs,可访问键或用 (; kwargs...) 转成具名元组。位置形参尾部的 more... 收集剩余实参为元组。调用时可用 ... 将元组或可迭代值展开。
函数值、组合和资源释放
x -> 表达式 构造匿名函数,多参数用 (x,y,z),无参数用 ()。map 可把函数应用到集合各项,filter 保留谓词为真的项。do 块把匿名函数作为外层调用的第一个参数,适合多行函数。
使用 open(path,mode) do io 后,Julia 在回调退出时关闭文件,包括正常返回与抛异常两种路径。本站例程实际写入临时文件并观察关闭状态。∘ 从右到左组合函数,|> 把前一步的值传给后一步。
f.(A) 按广播规则求值,支持多个参数,点调用可融合。目标 .= 形式会写入已有容器。内层函数可捕获外层绑定。递归必须设终止条件;朴素斐波那契会重复计算,可用缓存或迭代改写。
函数实例:采样摘要、关键字参数和临时文件
include(joinpath(@__DIR__, "observations.jl"))
function combine_readings(x,y)
x+y
end
function valid_reading(n)
n < 0 && return false
true
end
diagonal(x,y) = sqrt(x^2+y^2)
Σ(x,y) = x+y
fn = combine_readings
probe("function_definition",(7,11,-4),(combine_readings(7,11),valid_reading(7),valid_reading(-4),
diagonal(5,12),fn(7,11),fn===combine_readings,Σ(7,11)),(18,true,false,13.0,18,true,18))
fib_int(n::Integer) = n<2 ? n : fib_int(n-1)+fib_int(n-2)
function small_product(x,y)::Int8
return x*y
end
probe("function_dispatch",(7,1.5,5,6,64,2),
(fib_int(7),outcome(() -> fib_int(1.5)),small_product(5,6),typeof(small_product(5,6)),
outcome(() -> small_product(64,2))),
(13,"MethodError",Int8(30),Int8,"InexactError"))
stats(x,y) = (x+y,x*y)
sum_readings,product = stats(7,11)
function add_sample!(samples,value)
push!(samples,value)
return nothing
end
samples=Int[]
side_result=add_sample!(samples,7)
probe("function_return",(7,11),(sum_readings,product,side_result,samples),(18,77,nothing,[7]))
values(x,y,z=0)=(x,y,z)
probe("function_optional",(7,11,13),(values(7,11),values(7,11,13),length(methods(values))),
((7,11,0),(7,11,13),2))
report(x,y; limit=20, unit="counts")=(x,y,limit,unit)
probe("function_keywords",(7,11,31,"visits"),
(report(7,11),report(7,11;limit=31,unit="visits"),report(7,11,unit="visits",limit=31),
report(limit=31,7,11),outcome(() -> report(7,11;unknown=4))),
((7,11,20,"counts"),(7,11,31,"visits"),(7,11,31,"visits"),(7,11,31,"counts"),"MethodError"))
collect_options(x; y=0, kwargs...)=(x,y,kwargs,(;kwargs...))
a,b,extras,named=collect_options(7; north=31, south=41)
probe("function_kwargs",(7,31,41),(a,b,extras isa Base.Pairs,extras[:north],named),
(7,0,true,31,(north=31,south=41)))
arguments(a,b,more...)=(a,b,more)
probe("function_varargs",(7,11,(13,17)),(arguments(7,11),arguments(7,11,13,17),arguments(7,11,(13,17)...),
max([7,17,11]...)),((7,11,()),(7,11,(13,17)),(7,11,(13,17)),17))
polynomial = x -> x^2 + 2x - 1
alternate = function(x)
x^2 + 2x - 1
end
mix = (x,y,z) -> 2x+y-z
constant = () -> 7
probe("function_anonymous",(-2,0,3),(polynomial(3),alternate(3),mix(7,11,13),constant(),
map(round,[1.2,3.5,1.7]),map(polynomial,[1,3,-1])),(14,14,12,7,[1.0,4.0,2.0],[2,14,-2]))
xs=[-4,0,7]
a1=map(x -> x<0 ? 0 : x==0 ? 1 : x, xs)
a2=map(xs) do x
if x < 0
return 0
elseif x == 0
return 1
end
x
end
probe("function_do_map",xs,(a1,a2),([0,1,7],[0,1,7]))
mktempdir() do dir
path=joinpath(dir,"station.txt")
saved=Ref{IO}()
written=open(path,"w") do io
saved[]=io
write(io,"harbor\n")
end
closed_after_success=!isopen(saved[])
failure=outcome() do
open(path,"a") do io
saved[]=io
write(io,"wind\n")
error("demonstrate exceptional exit")
end
end
probe("function_do_io","open, write, return; reopen, write, throw",
(written,closed_after_success,failure,!isopen(saved[]),read(path,String)),
(7,true,"ErrorException",true,"harbor\nwind\n"))
end
probe("function_compose",("sea wind","3+6"),((sqrt∘+)(3,6),
map(first∘reverse∘uppercase,split("sea wind"))),(3.0,['A','D']))
probe("function_pipe",1:8,(1:8 |> sum |> sqrt),6.0)
xs_float=[1.0,2.0,3.0]
weights=[7,11,13]
scaled(x,y)=3x+4y
target=zeros(3)
target .= 2 .* scaled.(xs_float,weights)
probe("function_broadcast",(xs_float,weights),(sin.(xs_float)≈broadcast(sin,xs_float),
scaled.(xs_float,weights),target),(true,[31.,50.,61.],[62.,100.,122.]))
probe("function_map", [7,3,-2],map(x->x^3+3x-3,[7,3,-2]),[361,33,-17])
probe("function_filter",1:8,filter(iseven,collect(1:8)),[2,4,6,8])
function nested_reading(x)
doubled=2x
adjust()=doubled+1
adjust()
end
series(n)=n>1 ? series(n-1)+n : n
fib(n)=n<2 ? n : fib(n-1)+fib(n-2)
function fib_iter(n)
a,b=0,1
for _ in 1:n
a,b=b,a+b
end
a
end
probe("function_closure",10,nested_reading(10),21)
probe("function_recursive_sum",8,(series(8),series(1)),(36,1))
probe("function_recursive_fib",(0,8,16),(fib(0),fib(8),fib(16),fib_iter(16)),(0,21,987,987))
- 7 和 11 的和为 18、积为 77。关键字缺省及显式传参均实际观察。do 块正常或抛异常时,文件都已关闭,并留下写入的两行。
所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录
当前源码 SHA256:79683dfd780b05e78de5349eb3b0a002b119054430ae11ff4e5bf965f4dae446
本机练习工程
解压后按 README 分别运行三个脚本,使用 Julia 随附标准库。
所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录
ZIP SHA256:85a1ef1c4564938ca8d91588b78108e02f1dbe660a27e54310b2ba965497d9b4
常见错误与边界
- 返回类型注解会转换结果。若需要限制参与调用的参数类型,应写在形参上。
练习与解答
kwargs... 为什么可以再展开成具名元组?
展开参考解答
它按关键字名提供键值对,可用 (; kwargs...) 构造具名元组。