我正在学习 Erlang 并尝试使用 Dialyzer 在可能的情况下获得最大的类型安全性。有一件事我不明白:什么是非终止函数的类型以及如何在-spec
. 任何人都可以对此有所了解吗?
问问题
549 次
2 回答
8
永远循环且永不终止的函数具有返回类型no_return()
。(该返回类型也用于总是抛出异常的函数,例如自定义错误函数。如果您不指定该返回类型,Dialyzer 会告诉您该函数“没有本地返回”。)
Erlang Reference Manual 的Types and Function Specifications章节中提到了这一点:
Erlang 中的一些函数并不意味着返回;要么是因为它们定义了服务器,要么是因为它们用于抛出异常,如以下函数所示:
my_error(Err) -> erlang:throw({error, Err}).
对于此类功能,建议
no_return()
通过以下形式的合约使用特殊类型作为其“回报”:-spec my_error(term()) -> no_return().
于 2016-05-12T11:20:43.817 回答
0
以下示例在 Elixir 中,但我相信它们也清楚地为 Erlangers 使用no_return
和none
在 typespecs 中:
defmodule TypeSpecExamples do
@moduledoc """
Examples of typespecs using no_return and none.
"""
@spec forever :: no_return
def forever do
forever()
end
@spec only_for_side_effects :: no_return
def only_for_side_effects do
IO.puts "only_for_side_effects"
:useless_return_value # delete this line to return the value of the previous line
end
@spec print_dont_care :: no_return
def print_dont_care do
IO.puts("""
A no_return function that does not loop always returns a value, \
which can be anything, such as the atom #{only_for_side_effects()}
""")
end
@spec always_crash :: none
def always_crash do
raise "boom!"
end
@spec value_or_crash(boolean) :: number | none
def value_or_crash(b) do
if b do
1
else
raise "boom!"
end
end
end
于 2018-03-22T17:30:52.463 回答