Tas*_*nou 3 const strong-typing julia
一个.
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"
Run Code Online (Sandbox Code Playgroud)
为什么const关键字在这里没有按预期工作?(即,禁止指定y已声明为的字符串const).
湾
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
Run Code Online (Sandbox Code Playgroud)
为什么定义x为const上线3影响的值x上线2?
C.
特别是,这阻止我做:
function f(x::Float64)
const x = x; # ensure x cannot change type, to simulate "strong typing"
x = "This should throw an error";
end
Run Code Online (Sandbox Code Playgroud)
关于Lyndon的"反例"评论,我打算提供这个作为模拟"强类型"的方法,但它适用于我,因为这个功能在第2行而不是第3行突破,正如我预期的那样.
是什么导致了这种行为?这会被视为错误还是故意行为?
除了命名约定,是否有更可接受的方法来防止传递给函数的参数改变其类型?
(因为,是否有一个定义和适当的方法来做到这一点:我不是在解决方法之后,例如创建一个将x转换为不可变类型等的包装器)
编辑:
到目前为止,这是允许我在函数中强制执行const的唯一变体,但它仍然需要引入一个新的变量名:
julia> function f(x::Float64)
const x_const::Float64 = x;
x_const = "helle"; # this will break, as expected
end
Run Code Online (Sandbox Code Playgroud)
但即使这样,错误只是抱怨"从字符串到浮点的无效转换"而不是"对常量的无效重新定义"