Julia 方法与多重派发
观察多个参数共同决定的方法选择、交叉歧义、抽象接口和归一化。
学完这一章,你能够
- 观察多个参数共同决定的方法选择、交叉歧义、抽象接口和归一化。
函数和方法的关系
一个泛型函数可以有多个方法。调用时考虑各位置参数类型并寻找最具体的适用方法。Float64 对可命中更具体的方法,混合数值可落到 Number。没有匹配方法时抛 MethodError,methods 可查看当前方法表。
当两个方法各自在不同位置更具体时,交叉的实参组合可能发生歧义。为交集添加更具体的方法可明确行为。本站同时核对错误类型、诊断及修复后的返回。
类型参数、接口和扩展
where 可以把参数的类型绑定关联起来,或约束为 Number 的子类型。接受 Vector{T} 和一个 T 的方法会拒绝不匹配的元素值类型。Vector{<:Real} 可接受多个实数元素类型。
可以给抽象类型写公共接口逻辑,并为各具体类型实现必要方法。大多数算术运算符是函数,能够赋给变量或传入高阶函数。可为自己的类型用 Base.:+ 添加方法,也可以先显式 import 再定义未限定名称的方法。
同时改写别人定义的函数和类型会让其它调用方受影响。本站用两个自有教学模块观察同签名替换的效果,真实 Base 类型的现有方法保持独立。
混合类型的归一化
可将不同实参通过 promote 归一为共同类型,再调用同类型方法。兜底方法要确保转换后确实能命中更具体的方法,避免反复调用自身。若共有多种表示形式,也可用自有转换函数统一成单一表示,再实现核心逻辑。
设计方法
| 建议 | 实际条件 |
|---|---|
| 参数类型宁宽勿窄 | 接口接受整数时可标注 Integer,实测 BigInt 也能调用。 |
| 消除歧义要趁早 | 两个签名相交且互不更具体时,为交集定义明确方法。 |
| 避免派发抽象容器元素类型 | 需要多个实数元素类型时,考虑 Vector{<:Real}。Vector{Int} 和 Vector{Real} 各自有明确适用范围。 |
| 给接口函数写兜底方法 | 共享逻辑可放在抽象类型方法中,再调用各具体类型需实现的接口。 |
派发实例:复现歧义并验证修复
include(joinpath(@__DIR__, "observations.jl"))
reading(x::Float64,y::Float64)=2x+y
reading(x::Number,y::Number)=2x-y
probe("method_dispatch",(7,11),(reading(7.0,11.0),reading(7,11.0),reading(7,11),
outcome(() -> reading("bay","hill")),length(methods(reading))),
(25.0,3.0,3,"MethodError",2))
route(x::Float64,y)=2x+y
route(x,y::Float64)=x+2y
diagnostic=try
route(7.0,11.0)
catch err
(err isa MethodError,occursin("ambiguous",sprint(showerror,err)))
end
probe("method_ambiguous",(7.0,11.0),(route(7.0,11),route(7,11.0),diagnostic),(25.0,29.0,(true,true)))
route(x::Float64,y::Float64)=2x+2y
probe("method_disambiguated",(7.0,11.0),(route(7.0,11.0),length(methods(route))),(36.0,3))
same(x::T,y::T) where {T}=true
same(x,y)=false
same_numeric(x::T,y::T) where {T<:Number}=true
appended(v::Vector{T},x::T) where {T}=[v...,x]
probe("method_where",(7,11,11.0),(same(7,11),same(7,11.0),same_numeric(7,11),
outcome(() -> same_numeric("N","S"))),(true,false,true,"MethodError"))
probe("method_tied_parameters",([7,11],13,13.5),(appended([7,11],13),outcome(() -> appended([7,11],13.5))),
([7,11,13],"MethodError"))
sum_count(x::Integer)=x+1
take_readings(v::Vector{<:Real})=sum(v)
probe("method_broad_integer",big(7),(sum_count(big(7)),typeof(sum_count(big(7))),outcome(() -> sum_count(7.0))),
(big(8),BigInt,"MethodError"))
probe("method_vector_signature",([7,11],Real[7,11.0]),(take_readings([7,11]),take_readings(Real[7,11.0]),
outcome(() -> take_readings(["N","S"]))),(18,18.0,"MethodError"))
abstract type Region end
struct RoundRegion <: Region
radius::Float64
end
struct RectRegion <: Region
width::Float64
height::Float64
end
area(region::RoundRegion)=pi*region.radius^2
area(region::RectRegion)=region.width*region.height
describe(region::Region)=("area",area(region))
probe("method_interface","two Region subtypes",(last(describe(RoundRegion(2)))≈4pi,describe(RectRegion(3,7))),
(true,("area",21.0)))
op=+
probe("method_operator_value",(7,11,13),(7+11+13,+(7,11,13),op(7,11)),(31,31,18))
struct Offset
x::Float64
y::Float64
end
Base.:+(a::Offset,b::Offset)=Offset(a.x+b.x,a.y+b.y)
shifted=Offset(7,11)+Offset(13,17)
probe("method_owned_extension","two owned Offset records",(shifted.x,shifted.y),(20.0,28.0))
module LocalOwner
struct Marker
name::Symbol
end
inspect(x::Marker)=(:initial,x.name)
end
owned=LocalOwner.Marker(:bay)
before=LocalOwner.inspect(owned)
module LocalIntruder
import ..LocalOwner
LocalOwner.inspect(x::LocalOwner.Marker)=(:modified,x.name)
end
probe("method_owned_piracy_model","two local teaching modules",(before,LocalOwner.inspect(owned)),
((:initial,:bay),(:modified,:bay)))
function blend(x::T,y::T) where {T<:Real}
x*y
end
blend(x::Real,y::Real)=blend(promote(x,y)...)
probe("method_promote",(7,1.5),(blend(7,1.5),typeof(blend(7,1.5)),blend(7,11)),(10.5,Float64,77))
struct Distance
meters::Float64
end
as_distance(x::Distance)=x
as_distance(x::Real)=Distance(Float64(x))
difference(x::Distance,y::Distance)=x.meters-y.meters
difference(x,y)=difference(as_distance(x),as_distance(y))
probe("method_normalize",(7,11),(difference(Distance(7),11),difference(7,Distance(11)),
difference(7,11),outcome(() -> difference("north",11))),(-4.0,-4.0,-4.0,"MethodError"))
- 两个交叉签名在两个 Float64 参数上报歧义。添加交集方法后,输入 7.0 和 11.0 得 36.0。BigInt 输入可以走 Integer 接口。
所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录
当前源码 SHA256:902e5ea0da5f96b6fff42b4eb007d477f74d768342b5da1f3f2954cc29685cc8
本机练习工程
解压后分别执行两个脚本。练习只修改自己定义的类型或教学模块。
所需环境:Julia 1.10.13 官方便携版,Windows x64,本机隔离目录
ZIP SHA256:076c230015b28711d96f6ac9628944f4c7827173d21bc6fb95271cb4215f6a40
常见错误与边界
- 为歧义添加方法时应同时检查交集之外的两边原有行为。
练习与解答
仅增加 g(x::Number,y::Number) 能否解决 Float64 交叉歧义?
展开参考解答
不能。仍需一个比两个冲突签名更具体并覆盖交集的方法。