《Erlang程序设计》 第九章 练习题答案
第4题答案
这里仅仅作为演示,所以并未对里面的函数做具体的实现
%a.erl
-module(a).
-export_type([rich_text/0]).
-export([make_text/1,bounding_box/1]).
%-opaque rich_text() :: [{font(),char()}]. %第一行
% -type rich_text() :: [{font(),char()}]. %第二行
-type font() :: integer().
-spec make_text(string()) -> rich_text().
make_text(_Data) ->
[{1,98}].
-spec bounding_box(rich_text()) -> {Height :: integer(),Width :: integer()}.
bounding_box(_Text) -> {2,4}.
使用a模块函数的另一个模块为:
b.erl
-module(b).
-export([fonts_str/1]).
-import(a,[make_text/1]).
fonts_str(Str) ->
X = make_text(Str),
[F || {F,_} <- X].
首先我们放开第一行并且注释第二行,表示声明了一个rich_text的不透明类型。
使用dialyzer分析就会出现下面结果:
dialyzer a.erl b.erl
Checking whether the PLT c:/Users/26274/.dialyzer_plt is up-to-date... yes
Proceeding with analysis...
b.erl:5:1: Function fonts_str/1 has no local return
b.erl:7:5: The created fun has no local return
b.erl:7:5: The attempt to match a term of type
a:rich_text() against the pattern
[{F, _} | _] breaks the opacity of the term
b.erl:7:5: The attempt to match a term of type
a:rich_text() against the pattern
[] breaks the opacity of the term
b.erl:7:20: Fun application with arguments
(X :: a:rich_text()) will never return since it differs in the 1st argument from the success typing arguments:
([any()])
done in 0m0.28s
done (warnings were emitted)
然后我们注释第一行并且放开第二行,表示声明了一个rich_text的透明类型。
使用dialyzer分析就会出现下面的结果:
dialyzer a.erl b.erl
Checking whether the PLT c:/Users/26274/.dialyzer_plt is up-to-date... yes
Proceeding with analysis... done in 0m0.26s
done (passed successfully)
注意:此处请同时分析a,b两个模块。如果单单运行dialyzer b.erl,会出现找不到a模块中函数的错误。