I would like to write this function:
is_almost_zero(x::T)::Bool where {T<:Real} = x ≈ zero(T)
This code, however, results in an error:
julia> is_almost_zero(x::T)::Bool where {T<:Real} = x ≈ zero(T)
ERROR: UndefVarError: T not defined
Stacktrace:
[1] top-level scope
@ REPL[7]:1
Using the "full" syntax for function definitions works fine:
julia> function is_almost_zero(x::T)::Bool where {T<:Real}
x ≈ zero(T)
end
is_almost_zero (generic function with 1 method)
Omitting the return type also works:
julia> is_almost_zero(x::T) where {T<:Real} = x ≈ zero(T)
is_almost_zero (generic function with 1 method)
A similar working example is given in the docs about parametric methods: mytypeof(x::T) where {T} = T
.
However, I would like to specify the return type, but apparently I can't. The error message doesn't tell me which part of the expression causes the error, but the error itself looks similar to the case where I don't specify the where
part:
julia> is_almost_zero(x::T)::Bool = x ≈ zero(T)
ERROR: UndefVarError: T not defined
Stacktrace:
[1] top-level scope
@ REPL[23]:1
So it looks like Julia doesn't "see" the where {T<:Real}
part in my original code?
According to the documentation, the full syntax and the "assignment form" should be identical:
The traditional function declaration syntax demonstrated above is equivalent to the following compact "assignment form"
Answers to this question say that these two ways of defining a function are "functionally identical" and "equivalent".
How do I specify the return type of a one-line parametric function like this?
is_almost_zero(x::T)::Bool where {T<:Real} = x ≈ zero(T)
There's just a problem with parsing one-liners when there's a return type annotation, you can use parentheses to help the parser figure it out:
(is_almost_zero(x::T)::Bool) where {T<:Real} = x ≈ zero(T)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With