Erlang中带注解元组类型的用例是什么?

hmmo2u0o  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(118)

I found the below type specification in Erlang module. I am trying to understand how is it used? Is it similar to record?

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

lx0bsm1f1#

I found the below type specification in Erlang module. I am trying to understand how is it used? Is it similar to record?

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

No, it is a user defined type.
...types can be used to specify types of record fields and also the argument and return types of functions.
Type information can be used for the following:
To document function interfaces
To provide more information for bug detection tools, such as Dialyzer
To be exploited by documentation tools, such as EDoc, for generating program documentation of various forms
For more information about types, see:
http://erlang.org/doc/reference_manual/typespec.html
and:
https://learnyousomeerlang.com/dialyzer
Here is an example:

-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}.

In the shell:

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}

Dialyzer:

~/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)

相关问题