#`where` type syntax not working for return type annotations in methods

1 messages · Page 1 of 1 (latest)

keen dune
#
module research
    fib(x::T) where T<:Integer = 
        (x <= 1) ? 
            one(x) :
            fib(x - 2) + fib(x - 1)
end

seems to work fine, however

module research
    fib(x::T)::T where T<:Integer = 
        (x <= 1) ? 
            one(x) :
            fib(x - 2) + fib(x - 1)
end

fails with

runic jasper
#

It works when using function syntax
not sure why, would need someone with more knowledge to explain

keen dune
fringe nacelle
#

In this syntax I thought you had to use begin end

#

Wait nevermind it could just be my phone formatting. What if the T definition is surrounded in curly braces?

tribal widget
#

Looks like a parsing issue. Putting parentheses around that seems to work:

(fib(x::T)::T)
frigid saffron
#
julia> @Meta.lower  fib(x::T)::T where T<:Integer =
               (x <= 1) ?
                   one(x) :
                   fib(x - 2) + fib(x - 1)
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope`
1 ─      $(Expr(:thunk, CodeInfo(
    @ none within `top-level scope`
1return $(Expr(:method, :fib))
)))
│        $(Expr(:method, :fib))
│   %3 = Core.Typeof(fib)
│**   %4 = Core.svec(%3, T) **
│   %5 = Core.svec()
│   %6 = Core.svec(%4, %5, $(QuoteNode(:(#= REPL[4]:1 =#))))
│        $(Expr(:method, :fib, :(%6), CodeInfo(
    @ REPL[4]:1 within `none`
**1 ─ %1  = Core.TypeVar(:T, Integer)**
│  
...

Compare with:

julia> Meta.@lower fib(x::T) where T<:Integer =
               (x <= 1) ?
                   one(x) :
                   fib(x - 2) + fib(x - 1)
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope`
1 ─      $(Expr(:thunk, CodeInfo(
    @ none within `top-level scope`
1return $(Expr(:method, :fib))
)))
│        $(Expr(:method, :fib))
│**   %3 = Core.TypeVar(:T, Integer)**

In the 2nd version without type annotation, the TypeVar is determined before any other occurrence of T (there isn't any). But in the 1st one, you have %4 = Core.svec(%3, T) before the line %1 = Core.TypeVar(:T, Integer).

Why would this be? 🤔