Where Statements


I would like to understand the difference between multiple where statements and single where statement.

Can someone point me in the right direction or give me good answer?

Here is an example:

julia> function foo(x::T,y::U) where {T<:Real,U<:T}
foo (generic function with 1 method)

function tar(x::T,y::U) where U<:T where T<:Real

julia> function bar(x::T,y::U) where T<:Real where U<:T
ERROR: UndefVarError: T not defined


It is instructive to look what the parser turns your different variants into:

julia> :(function bar(x::T,y::U) where T<:Real where U<:T
:(function (bar(x::T, y::U) where T <: Real) where U <: T # REPL[7], line 2:
        x + y

This shows that each where statement creates a new level of nesting and in particular T here is only defined inside the inner nesting level, therefore you cannot reference it in the outer where statement.


My advice is that, in order to avoid confusion for yourself and others reading your code, you should avoid using nested where statements. It should almost never be necessary.

where {T<:Real, U<:T}

is equivalent to

where U<:T where T<:Real

in other words, the nesting order is reversed.