Erlang中非终止函数的类型

blpfk2vs  于 2022-12-16  发布在  Erlang
关注(0)|答案(2)|浏览(164)

我正在学习Erlang语言,并尝试使用透析器来尽可能地获得最大的类型安全。有一件事我不明白:什么是非终止函数的类型,以及如何在-spec中表示它。有人能解释一下吗?

qaxu7uf2

qaxu7uf21#

一个永远循环且永不终止的函数的返回类型为no_return()(该返回类型也用于总是抛出异常的函数,如自定义错误函数,如果不指定该返回类型,Dialyzer会告诉你该函数“没有本地返回”)。
Erlang参考手册的Types and Function Specifications章节中提到了这一点:
Erlang中的一些函数不是要返回的;这可能是因为它们定义了服务器,也可能是因为它们用于引发异常,如以下函数所示:

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

对于这样的函数,建议通过以下形式的契约,使用特殊的no_return()类型作为它们的“返回”:

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

pftdvrlh2#

下面的例子是用Elixir编写的,但我相信它们也使用了no_returnnone的类型规范,这对Erlangers来说也很清楚:

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

相关问题