Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying the return type of a one-line parametric function

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?

These ways of defining the function should be equivalent, though?

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".

Question

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)
like image 774
ForceBru Avatar asked Mar 02 '23 08:03

ForceBru


1 Answers

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)
like image 57
BatWannaBe Avatar answered Jun 05 '23 19:06

BatWannaBe