繁体   English   中英

为什么这个带有类型签名的 erlang prog 可以编译?

[英]Why this erlang prog with type signature can compile?

我有这个编:

-module(a).
-export([add/2]).
-export([add2/1]).

-spec add(integer(),integer())->integer().
add(A,B)->A+B.

add2(C)->C+add(1,"a").

我可以毫无错误地编译这个 prog。但我认为我应该得到该行的错误

add(1,"a").

在任何 static 类型的语言中,它都无法编译,那么为什么 erlang 会编译这个?如何
编写类型签名,以便 erlang 可以捕获此错误?如果 erlang 不能,elixir 可以编写相同的程序但可以捕获此错误吗?谢谢!

Erlang 不是静态类型语言,它始终是动态类型的。 您无法在编译期间捕获它,因为erlc根本不关心-spec 它仅用于文档和 Dialyzer(从技术上讲是外部工具)可以使用它对合约进行一些(有限的)static 分析。

有关如何使用 Dialyzer,请查看:

Erlang 编译器不检查类型规范。 您可以使用 Erlang 中包含的 Dialyzer 来检查它们:

dialyzer --src a.erl

它给出了以下 output:

  Proceeding with analysis...
a.erl:8: Function add2/1 has no local return
a.erl:8: The call a:add
         (1,
          "a") will never return since the success typing is 
         (number(),
          number()) -> 
          number() and the contract is 
          (integer(), integer()) -> integer()
 done in 0m0.19s
done (warnings were emitted)

第一次运行 Dialyzer 时,它会抱怨它没有标准应用程序的 PLT(持久查找表)。 您可以使用以下方法构建它:

dialyzer --build_plt --apps erts kernel stdlib mnesia

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM