Prompted by Lyndon's question earlier today:
a.
julia> function f1(x::Float64)
const y = x;
y = "This should throw an error since y is of constant type";
return y;
end
f1 (generic function with 1 method)
julia> f1(1.0)
"This should throw an error since y is of constant type"
Why does the const
keyword not work as expected here? (i.e., disallow assigning a string to y
which has been declared as const
).
b.
julia> function f2(x::Float64)
show(x);
const x = 1.;
end
f2 (generic function with 1 method)
julia> f2(1.0)
ERROR: UndefVarError: x not defined
Stacktrace:
[1] f2(::Float64) at ./REPL[1]:2
Why does defining x
as const
on line 3 affect the value of x
on line 2?
c.
In particular, this prevents me from doing:
function f(x::Float64)
const x = x; # ensure x cannot change type, to simulate "strong typing"
x = "This should throw an error";
end
I was going to offer this as a way to simulate "strong typing", with regard to Lyndon's "counterexample" comment, but it backfired on me, since this function breaks at line 2, rather than line 3 as I expected it to.
What is causing this behaviour? Would this be considered a bug, or intentional behaviour?
Naming conventions aside, is there a more acceptable way to prevent an argument passed into a function from having its type altered?
(as in, is there a defined and appropriate way to do this: I'm not after workarounds, e.g. creating a wrapper that converts x to an immutable type etc)
EDIT:
So far, this is the only variant that allows me to enforce constness in a function, but it still requires the introduction of a new variable name:
julia> function f(x::Float64)
const x_const::Float64 = x;
x_const = "helle"; # this will break, as expected
end
but even then, the error just complains of an "invalid conversion from string to float" rather than an "invalid redefinition of a constant"
Julia has a sophisticated type system and allows multiple dispatch on argument types. None of the examples given here provide any type annotations on their arguments, meaning that they are applicable to all types of arguments.
A type union is a special abstract type which includes as objects all instances of any of its argument types, constructed using the special Union keyword: julia> IntOrString = Union{Int,AbstractString} Union{Int64, AbstractString} julia> 1 :: IntOrString 1 julia> "Hello!"
When you declare a variable as const , you are just telling something about how that name shall be used. So, it doesn't matter what content you assign to var2 the first time. If you don't declare it as const , there is nothing stopping you from assigning it a different value – maybe of a different type – later on.
Because const
in local scope is not yet implemented:
https://github.com/JuliaLang/julia/issues/5148
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