Where Statements


#1

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}
           x+y
       end
foo (generic function with 1 method)

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

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

#2

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
                  x+y
              end)
:(function (bar(x::T, y::U) where T <: Real) where U <: T # REPL[7], line 2:
        x + y
    end)

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.


#3

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.


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

is equivalent to

where U<:T where T<:Real

in other words, the nesting order is reversed.