问题描述
今天早些时候由 Lyndon的问题提示:
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"
为什么const
关键字在这里不能按预期工作? (即,不允许为已声明为const
的y
分配字符串).
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
为什么在 3 行上将x
定义为const
会影响 2 行上x
的值?
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
针对Lyndon的"counterexample"注释,但它对我适得其反,因为此功能在第2行中断,而不是我期望的那样在第3行中断.
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?
到目前为止,这是允许我在函数中强制执行constness的唯一变体,但仍需要引入新的变量名:
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"
推荐答案
因为尚未实现本地范围内的const
:
Because const
in local scope is not yet implemented:
https://github.com/JuliaLang/julia/issues/5148
这篇关于为什么在这些julia函数中不尊重constness?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!