关于 "where" 的使用疑惑

为什么如下代码需要使用where 呢?

function mod(x::T, y::T) where T<:AbstractFloat
    r = rem(x,y)
    if r == 0
        copysign(r,y)
    elseif (r > 0) ⊻ (y > 0)
        r+y
    else
        r
    end
end

相比直接写成如下形式有何优点/特别考虑之处?

function mod(x::AbstractFloat, y::AbstractFloat)  

谢谢!

取决于如何设计多重派发

julia> f(x::T, y::T) where T = x + y
f (generic function with 1 method)

julia> g(x::Real, y::Real) = x + y
g (generic function with 1 method)

julia> f(1, 2)
3

julia> f(1.0, 2)
ERROR: MethodError: no method matching f(::Float64, ::Int64)
Closest candidates are:
  f(::T, ::T) where T at REPL[1]:1
Stacktrace:
 [1] top-level scope
   @ REPL[4]:1

julia> g(1, 2)
3

julia> g(1.0, 2)
3.0
1 个赞

第一种写法能保证函数的输入类型是一致的。如果用第二种写法,可能会有x是float64,而y是float32的情况。看你允不允许这种情况发生了。

3 个赞