为什么在这些 julia 函数中不尊重 constness? [英] Why is constness not respected inside these julia functions?
问题描述
今天早些时候由 Lyndon 的问题提示:
Prompted by Lyndon's question earlier today:
一个.
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
会影响x的值代码> 行 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
关于 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?
除了命名约定,有没有更可接受的方法来防止传递给函数的参数改变其类型?
(例如,是否有一种已定义且适当的方法来做到这一点:我不是在寻找变通方法,例如创建一个将 x 转换为不可变类型的包装器等)
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)
到目前为止,这是唯一允许我在函数中强制执行 const 的变体,但它仍然需要引入新的变量名:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!