Type of non-terminating function in erlang

时光毁灭记忆、已成空白 提交于 2019-12-12 12:13:53

问题


I'm learning erlang and trying to use dialyzer to get maximum type-safety when it's possible. There's a thing that I don't understand: what is the type of non-terminating function and how to denote it in spec. Could you please shed a light on this?


回答1:


A function that loops forever and never terminates has the return type no_return(). (That return type is also used for functions that always throw exceptions, e.g. a custom error function. If you don't specify that return type, Dialyzer will tell you that the function "has no local return".)

This is mentioned in the Types and Function Specifications chapter of the Erlang Reference Manual:

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().



回答2:


The following examples are in Elixir, but I believe they make the use of no_return and none in typespecs clear for Erlangers too:

 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


来源:https://stackoverflow.com/questions/37184719/type-of-non-terminating-function-in-erlang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!