`
argan
  • 浏览: 126153 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Erlang 基础学习 2 简单的程序

阅读更多
Erlang Sequential Programming

Modules

• 存放在.erl的文件里,需要先编译才能运行
• 代码的基本单元,所有的函数都存在module里
•    Bogdan’s Erlang Abstract Machine
• 在erlang shell 中,使用c(module_name).来编译和装载一个module
• 看代码
-module (geometry).
-export ([area/1]).

area({rectangle,Width,Height}) -> Width * Height;
area({circle,Radius}) -> 3.14159 * Radius * Radius.

• 上面代码中,执行area函数,实际上是匹配area各个实现的参数的过程,匹配到了,就执行函数体的内容,然后返回

Funs
• 高阶函数,返回函数,或者接受函数为参数的函数
• Double = fun(X) -> 2*X end.
• 246 = Z (123).

• [2,4,6,8] = lists:map(Double,[1,2,3,4]).
• lists:map,lists:filter
• 
• Fruit = [apple,pear,orange].
• MakeTest = fun(L) -> (fun(X) -> lists:member(X, L) end) end.
• IsFruit = MakeTest(Fruit).
• IsFruit(pear).
• lists:filter(IsFruit, [dog,orange,cat,apple,bear]).
• 
• lists 的快速操作方式
• L = [1,2,3,4].
• [2,4,6,8]=[2*X || X <- L ].
• [X || Q1,Q2,Q3...]
• Q1,Q2 是一些表达式,一种是产生内容的,例如 V <- [],另一种是过滤器,返回true/false的表达式
• 计算满足毕达哥拉斯表达式的数字组合
pythag(N) ->
    [ {A,B,C} ||
        A <- lists:seq(1,N),
        B <- lists:seq(1,N),
        C <- lists:seq(1,N),
        A+B+C =< N,
        A*A+B*B =:= C*C
    ].

数学表达式优先级

Guards
• guard sequence是由一系列的guard组成,用分号(;)分隔,G1;G2;G3 当至少一个为true是就为true
• guard 是由一一些guard表达式组成,用逗号(,)分隔,如Exp1,Exp2,Exp3,当所有表达式为true时,guard为true
• is_atom,is_integer ,is_系列

Record

-record(Name, {
                %% the next two keys have default values
                key1 = Default1,
                key2 = Default2,
                ...
                %% The next line is equivalent to
                %% key3 = undefined
                key3,
                ...
              }).

• record 只能在erl module里使用,不能在shell里使用
• 所有的key必须是 atom
• X1 = #todo{status=urgent,text="adfadfa"}.
• X2 = X1#todo{status=done}. %  拷贝X1,然后将status赋值
• record的值的取得可以通过pattern match来取得,不提
• 另外,如果只需要一个字段的值,可以使用 X2#todo.text. 来获取
• 本质上,record是保存为一个tuple的,在shell里使用rf(todo).来删除shell里todo这个record,这时候,查看X2的值是{todo,gogogo,argan,undefined},第一个是record的名字,后面是按顺序保存的每个字段的值
• 具体使用,例如:
clear_status(#todo{status=S, who=W} = R) when is_record(R,todo) ->
    %% Inside this function S and W are bound to the field
    %% values in the record
    %%
    %% R is the *entire* record
    R#todo{status=finished}
    %% ...

case 和if 表达式

case Expression of
    Pattern1 [when Guard1] -> Expr_seq1;
    Pattern2 [when Guard2] -> Expr_seq2;
    ...
end

if
   Guard1 ->
     Expr_seq1;
   Guard2 ->
     Expr_seq2;
   ...
end


• 总是优先使用系统提供的函数,例如lists:reverse/1



分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics