首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

<20>erlang中的门类和函数说明

2013-09-28 
20erlang中的类型和函数说明erlang是一种动态类型的语言(运行时才决定数据类型),可以自己声明一些数据类

<20>erlang中的类型和函数说明
erlang是一种动态类型的语言(运行时才决定数据类型),可以自己声明一些数据类型
(1) 预定义类型
首先erlang自己有一套预定义的数据类型, 也可以有用户自己定义的类型,自己定义的类型都来源于这些预定义的类型的组合及类型定义的语法,
预定义类型:
Type :: any()            %% The top type, the set of all Erlang terms.
      | none()           %% The bottom type, contains no terms.
      | pid()
      | port()
      | reference()
      | []               %% nil
      | Atom
      | Binary
      | float()
      | Fun
      | Integer
      | List
      | Tuple
      | Union
      | UserDefined      %% described in Section 2

Union :: Type1 | Type2
Atom :: atom()
      | Erlang_Atom      %% 'foo', 'bar', ...
Binary :: binary()                        %% <<_:_ * 8>>
        | <<>>
        | <<_:Erlang_Integer>>            %% Base size
        | <<_:_*Erlang_Integer>>          %% Unit size
        | <<_:Erlang_Integer, _:_*Erlang_Integer>>
Fun :: fun()                              %% any function
     | fun((...) -> Type)                 %% any arity, returning Type
     | fun(() -> Type)
     | fun((TList) -> Type)
Integer :: integer()
         | Erlang_Integer                 %% ..., -1, 0, 1, ... 42 ...
         | Erlang_Integer..Erlang_Integer %% specifies an integer range
List :: list(Type)                        %% Proper list ([]-terminated)
      | improper_list(Type1, Type2)       %% Type1=contents, Type2=termination
      | maybe_improper_list(Type1, Type2) %% Type1 and Type2 as above
Tuple :: tuple()                          %% stands for a tuple of any size
       | {}
       | {TList}
TList :: Type
       | Type, TList

(2) 内置的一些类型:
一些联合类型的,是erlang系统已经定义好的,可以认为是自定义的, 当然erlang已经有的类型名字,我们自己不可以再次使用,编译时候会对这些类型进行检查:
Built-in typeStands for
term()any()
boolean()'false' | 'true'
byte()0..255
char()0..16#10ffff
non_neg_integer()0..
pos_integer()1..
neg_integer()..-1
number()integer() | float()
list()[any()]
maybe_improper_list()maybe_improper_list(any(), any())
maybe_improper_list(T)maybe_improper_list(T, any())
string()[char()]
nonempty_string()[char(),...]
iolist()maybe_improper_list(char() | binary() | iolist(), binary() | [])
module()atom()
mfa(){atom(),atom(),byte()}
node()atom()
timeout()'infinity' | non_neg_integer()
no_return()none()

(3)用户自定义类型:
自己定义的类,必须引用已经有的预定义类型,或者已经定义过的类型,或者其他模块导出的类型,自定义类型的模板:-type my_struct_type() :: Type.
例如自己定一个int型,
-type int() :: integer(). 
这里integer() 必须是已经有的类型

(4)应用:
程序中的函数说明的通常用法,用这种方法更通用,结构固定,容易理解,
格式如下: -spec Module:Function(ArgType1, ..., ArgTypeN) -> ReturnType.
例如自己定义一个int(), 并且给test/1函数进行说明:
-module(test).
-compile(export_all).
-type int() :: integer().                                                               
<1> -spec test:test(integer()) -> integer().
<2> -spec test:test(A) -> A when
        A::integer().
<3> -spec test:test(int()) -> int().
test(A) when is_integer(A) ->
    A. 
这三种方法都可以,方法<3>用了自己定义的类型int().                       


热点排行