Why is constness not respected inside these julia functions?

柔情痞子 提交于 2019-12-07 17:40:38

问题


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"


回答1:


Because const in local scope is not yet implemented:

https://github.com/JuliaLang/julia/issues/5148



来源:https://stackoverflow.com/questions/42422209/why-is-constness-not-respected-inside-these-julia-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!