首页 > 解决方案 > Erlang中带注释的元组类型的用例是什么?

问题描述

我在 Erlang 模块中找到了以下类型规范。我想了解它是如何使用的?和录音类似吗?

-type timestamp() :: {MegaSecs :: non_neg_integer(),
                      Secs :: non_neg_integer(),
                      MicroSecs :: non_neg_integer()}.

标签: erlang

解决方案


我在 Erlang 模块中找到了以下类型规范。我想了解它是如何使用的?和录音类似吗?

-type timestamp() :: {MegaSecs :: non_neg_integer(),
                      Secs :: non_neg_integer(),
                      MicroSecs :: non_neg_integer()}.

不,它是用户定义的类型。

...类型可用于指定记录字段的类型以及函数的参数和返回类型。

类型信息可用于以下方面:

记录功能接口
为错误检测工具(例如 Dialyzer)提供更多信息
被文档工具(例如 EDoc)利用,用于生成各种形式的程序文档

有关类型的更多信息,请参阅:

http://erlang.org/doc/reference_manual/typespec.html

和:

https://learnyousomeerlang.com/dialyzer

这是一个例子:

-module(a).
-compile(export_all).

-type timestamp() :: {MegaSecs :: non_neg_integer(),
                      Secs :: non_neg_integer(),
                      MicroSecs :: non_neg_integer()}.

-record(bill, {name :: string(),
               amount :: non_neg_integer(),
               date :: timestamp() 
              }
        ).
-type bill() :: #bill{}.

-spec payment_due(bill()) -> timestamp().
payment_due(Bill) ->
    {Mega, Sec, Micro} = Bill#bill.date,
    {Mega+1, Sec, Micro}.

在外壳中:

1> c(a).                                                        
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}

2> rr(a).                                                       
[bill]

3> Bill = #bill{name="John", amount=30, date={3, 2, 1}}.
#bill{name = "John",amount = 30,date = {3,2,1}}

4> a:payment_due(Bill).                                         
{4,2,1}

透析器:

~/erlang_programs$ dialyzer --build_plt --apps erts kernel stdlib crypto mnesia sasl commotest eunit
  Compiling some key modules to native code... done in 0m35.60s
  Creating PLT /Users/7stud/.dialyzer_plt ...
...
...
done (passed successfully)

~/erlang_programs$ dialyzer a.erl
  Checking whether the PLT /Users/7stud/.dialyzer_plt is up-to-date... yes
  Proceeding with analysis... done in 0m0.15s
done (passed successfully)

推荐阅读