julialang:可以(应该)在编译时捕获这种类型的错误吗?

问题描述:

function somefun()
    x::Int = 1
    x = 0.5
end

此编译没有警告.当然调用它会产生一个InexactError:Int64(0.5).问题:您可以强制执行编译时检查吗?

this compiles with no warning. of course calling it produces an InexactError: Int64(0.5). question: can you enforce a compile time check?

Julia在这种意义上是一种动态语言.因此,不,您似乎无法在不先运行函数的情况下检测到赋值的结果是否会导致此类错误,因为这种类型检查是在运行时完成的.

Julia is a dynamic language in this sense. So, no, it appears you cannot detect if the result of an assignment will result in such an error without running the function first, as this kind of type checking is done at runtime.

我不确定自己,所以我在没有运行该函数的情况下将该函数包装在模块中以强制(预)编译,结果是未引发任何错误,这证实了这一想法. (如果要了解我的意思,请参见此处).

I wasn't sure myself, so I wrapped this function in a module to force (pre)compilation in the absence of running the function, and the result was that no error was thrown, which confirms this idea. (see here if you want to see what I mean by this).

已经这么说了,回答您问题的精神:有没有办法避免这种晦涩的运行时错误以意想不到的方式蔓延?

Having said this, to answer the spirit of your question: is there a way to avoid such obscure runtime errors from creeping up in unexpected ways?

是的.考虑以下两个几乎等效的功能:

Yes there is. Consider the following two, almost equivalent functions:

function fun1(x     ); y::Int = x; return y; end;
function fun2(x::Int); y::Int = x; return y; end;

fun1(0.5)   # ERROR: InexactError: Int64(0.5)
fun2(0.5)   # ERROR: MethodError: no method matching fun2(::Float64)

您可能会认为,大不了,我们将一个错误换成另一个.但这种情况并非如此.在第一种情况下,直到函数中使用输入之前,您都不知道输入会引起问题.而在第二种情况下,您可以在调用函数时有效地执行类型检查.

You may think, big deal, we exchanged one error for another. But this is not the case. In the first instance, you don't know that your input will cause a problem until the point where it gets used in the function. Whereas in the second case, you are effectively enforcing a type check at the point of calling the function.

这是利用Julia优雅的类型检查系统进行按合同"编程的简单示例.有关详细信息,请参见按合同设计.

This is a trivial example of programming "by contract", by making use of Julia's elegant type-checking system. See Design By Contract for details.

因此,您的问题的答案是,是的,如果您重新考虑设计并遵循良好的编程习惯,以便尽早发现此类错误,则可以避免在错误的场景中稍后再发生此类错误.难以修复或检测.

So the answer to your question is, yes, if you rethink your design and follow good programming practices, such that this kind of errors are caught early on, then you can avoid having them occuring later on in obscure scenarios where they are hard to fix or detect.

Julia手册提供了样式指南这可能也有帮助(我上面给出的示例恰好在顶部!).

The Julia manual provides a style guide which may also be of help (the example I give above is right at the top!).