-
The documentation states explicitly that “The default behavior in Julia when types are omitted is to allow values to be of any type. Thus, one can write many useful Julia functions without ever explicitly using types.” (see Types · The Julia Language, start of third paragraph).
-
Indeed, the input arguments of a function do not need to be defined explicitly before calling the function, and this lack of requirement allows the function to be used with different argument types:
julia> function f1(x, y)
x + y
end
f1 (generic function with 1 method)
julia> f1(1, 2)
3
julia> f1(1.2, 3.4)
4.6
- However, this flexibility apparently does not apply to output arguments:
julia> function f2(x, y, z)
z = x + y
return 0 # template for an error code
end
f2 (generic function with 1 method)
julia> f2(1, 2, z)
ERROR: UndefVarError: z not defined
Stacktrace:
[1] top-level scope
@ REPL[32]:1
even though it should be easy to infer the type of z from those of x an y.
- And it looks like considering an output argument as an optional argument with a pre-assigned type and default value is not acceptable either:
julia> function f3(x, y, z::Float64 = 0.0)
z = x + y
return 0
end
f3 (generic function with 2 methods)
julia> f3(1, 2, z)
ERROR: UndefVarError: z not defined
Stacktrace:
[1] top-level scope
@ REPL[34]:1
- Question: Why is it mandatory to pre-define the types of output arguments since they are computed inside the function? Output arguments are frequently used in C, FORTRAN, IDL and other such languages: it is cumbersome to require users to pre-define the type of output arguments when calling external functions in those languages (specifically ccall), especially because this requires a rather intimate knowledge of the exact requirements of those external functions, as well as a translation table between types in those two languages (as described in Calling C and Fortran Code · The Julia Language)…
Thanks for clarifying those points.