Erlang 中的非终止函数类型

Type of non-terminating function in Erlang

我正在学习 Erlang 并尝试使用 Dialyzer 在可能的情况下获得最大的类型安全性。有一件事我不明白:非终止函数的类型是什么以及如何在-spec中表示它。任何人都可以对此有所了解吗?

一个永远循环且永不终止的函数具有 return 类型 no_return()。 (return 类型也用于总是抛出异常的函数,例如自定义错误函数。如果您不指定 return 类型,Dialyzer 会告诉您该函数“没有本地 return".)

这个在Erlang参考手册的Types and Function Specifications章节中有提到:

Some functions in Erlang are not meant to return; either because they define servers or because they are used to throw exceptions, as in the following function:

my_error(Err) -> erlang:throw({error, Err}).

For such functions, it is recommended to use the special no_return() type for their "return", through a contract of the following form:

-spec my_error(term()) -> no_return().

以下示例在 Elixir 中,但我相信它们在 Erlangers 的类型规范中使用 no_returnnone 也很清楚:

 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