首页 Sequential Erlang

Sequential Erlang

举报
开通vip

Sequential Erlang Erlang Solutions Ltd. © 1999-2011 Erlang Solutions Ltd. Sequential Erlang © 1999-2011 Erlang Solutions Ltd. Overview: sequential Erlang I • Sequential Erlang I - Conditional Evaluation - Guards - Recursion • Sequential Erlang II • Sequential Erlang III ...

Sequential Erlang
Erlang Solutions Ltd. © 1999-2011 Erlang Solutions Ltd. Sequential Erlang © 1999-2011 Erlang Solutions Ltd. Overview: sequential Erlang I • Sequential Erlang I - Conditional Evaluation - Guards - Recursion • Sequential Erlang II • Sequential Erlang III 2 1 2 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: case case lists:member(foo, List) of true -> ok; false -> {error, unknown} end 3 © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: case case lists:member(foo, List) of true -> ok; false -> {error, unknown} end 3 case clauses 3 3 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: case case lists:member(foo, List) of true -> ok; false -> {error, unknown} end 3 expression © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: case case lists:member(foo, List) of true -> ok; false -> {error, unknown} end 3 patterns 3 3 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: case case lists:member(foo, List) of true -> ok; false -> {error, unknown} end 3 clause separator © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: case case lists:member(foo, List) of true -> ok; false -> {error, unknown} end 3 no separator in last clause 3 3 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. case of Pattern1 -> , , ... ; Pattern2 -> , , ... ; _ -> , ... end Conditional evaluation: case •One branch should always succeed •Using an unbound variable or '_' ensures that the clause will always match •The _ clause is not mandatory •An exception is raised if no clause matches •Returns the value of the last executed expression 4 © 1999-2011 Erlang Solutions Ltd. convert(Day) -> case Day of monday -> 1; tuesday -> 2; wednesday -> 3; thursday -> 4; friday -> 5; saturday -> 6; sunday -> 7; Other -> {error, unknown_day} end. Defensive Programming •Defensive programming: program in the convert function for the error case or ... •... let it fail here by deleting the Other clause. •This will raise an exception •The caller will have to handle the error that they have caused. 5 4 5 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: if if X < 1 -> smaller; X > 1 -> greater; X == 1 -> equal end 6 © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: if if X < 1 -> smaller; X > 1 -> greater; X == 1 -> equal end 6 if clauses 6 6 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: if if X < 1 -> smaller; X > 1 -> greater; X == 1 -> equal end 6 guard expressions © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: if if X < 1 -> smaller; X > 1 -> greater; X == 1 -> equal end 6 clause separator 6 6 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Conditional Evaluation: if if X < 1 -> smaller; X > 1 -> greater; X == 1 -> equal end 6 no separator in last clause © 1999-2011 Erlang Solutions Ltd. if Guard1 -> , , ... ; Guard2 -> , , ... ; ... true -> , ... end Conditional Evaluation: if •One branch must always succeed •By using true as the last guard, we ensure that a clause will always succeed •The true guard is not mandatory •An exception is raised if no clause succeeds •Returns the value of the last executed expression 7 6 7 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. factorial(N) when N > 0 -> N * factorial(N - 1); factorial(0) -> 1. This is NOT the same as... factorial(0) -> 1; factorial(N) -> N * factorial(N - 1). Guards •The reserved word when introduces a guard •Fully guarded clauses can be re-ordered •Guards can be used in function heads, case clauses, receive and if expressions. 8 © 1999-2011 Erlang Solutions Ltd. number(Num) when is_integer(Num) -> integer; number(Num) when is_float(Num) -> float; number(_Other) -> false. Guards: examples • is_number(X), is_integer(X), is_float(X) - X is a number • is_atom(X), is_pid(X), is_tuple(X), is_list(X) - X is the specified datatype • length(List) == Int, tuple_size(Tuple) == Size, X > Y + Z - Some BIFs and mathematical applications can be applied in guards • X == Y X /= Y X =:= Y X =/= Y - X is (not) equal to Y, X is exactly (not) equal to Y (1==1.0 ✓, 1=:=1.0 !) • X =< Y X >= Y - NB, not <= or => 9 8 9 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. valid_age(Age) when Age >= 18, Age =< 99 -> true; valid_age(_) -> false. Guards •All variables in guards have to be bound •Guards have to be free of side effects • If all the guards have to succeed, use , to separate them • If one guard has to succeed, use ; to separate them • There are restrictions on BIFs and expressions in guards - See the Erlang reference manual for complete details 10 © 1999-2011 Erlang Solutions Ltd. if f(Args) -> ok; true -> error end case f(Args) of true -> ok; false -> error end General Switch • The if construct fails because it involves a user-defined function, which are forbidden in guards • The case construct succeeds because it accepts user-defined functions. 11 X ✓ 10 11 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. average(X) -> sum(X) / len(X). sum([H|T]) -> H + Sum(T); sum([]) -> 0. len([_|T]) -> 1 + len(T); len([]) -> 0. Recursion: traversing lists •Note the pattern of recursion is the same in both cases •Taking a list and evaluating an element is a very common pattern 12 © 1999-2011 Erlang Solutions Ltd. sum([]) -> 0; sum([H|T]) -> H + sum(T). Recursion: self-describing code •You can read the programs as an executable description: •"The sum of an empty list is 0." •"The sum of a non-empty list is the head of the list added to the sum of the tail" 13 12 13 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. printAll([]) -> io:format("~n",[]); printAll([X|Xs]) -> io:format("~p ",[X]), printAll(Xs). Recursion: traversing lists •Here we're traversing the list imperatively: •"If there are no more elements to process, stop" •"If there are further elements, process the head, and then call the function recursively on the tail." 14 © 1999-2011 Erlang Solutions Ltd. printAll(Ys) -> case Ys of [] -> io:format("~n",[]); [X|Xs] -> io:format("~p ",[X]), printAll(Xs) end. Recursion: traversing lists •Same function again: shows the loop clearly. The call to printAll(Xs) is like a jump back to the top of the loop. •This is a tail recursive function: the only recursive calls come at the end of the bodies of the clauses. 15 14 15 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. double([H|T])-> [2*H|double(T)]; double([]) -> []. member(H, [H|_]) -> true; member(H, [_|T]) -> member(H,T); member(_, []) -> false. even([H|T]) when H rem 2 == 0 -> [H|even(T)]; even([_|T]) -> even(T); even([]) -> []. Recursion: more patterns •double/1 maps elements in a list and returns a new list •member/2 is a predicate looking for an element in a list •even/1 filters a list of integers and returns the subset of even numbers •The function member/2 is the only one which is tail recursive 16 © 1999-2011 Erlang Solutions Ltd. average(X) -> average(X,0,0). average([H|T], Length, Sum) -> average(T, Length+1, Sum+H); average([], Length, Sum) -> Sum/Length. Recursion: accumulators •Only traverses the list once. •Executes in constant space (tail recursive) •Length and Sum play the role of accumulators •average([]) is not defined •Evaluating average([]) would cause a run time error. 17 16 17 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Summary: sequential Erlang I • Sequential Erlang I - Conditional evaluation - Guards - Recursion • Sequential Erlang II • Sequential Erlang III 18 © 1999-2011 Erlang Solutions Ltd. Overview: sequential Erlang II • Sequential Erlang I • Sequential Erlang II - BIFs - Libraries - Manual Pages - The Debugger • Sequential Erlang III 19 18 19 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. date() time() length(List) size(Tuple) atom_to_list(Atom) list_to_tuple(List) integer_to_list(2235) tuple_to_list(Tuple) Built-in Functions •Do what you cannot do (or is difficult to do) in Erlang •Mostly written in C for fast execution •BIFs are by convention regarded as being in the erlang module. 20 © 1999-2011 Erlang Solutions Ltd. Built-in Functions •There are BIFs for: - Process and port handling - Object access and examination - Meta programming - Type conversion - System information - Distribution - Others • For a complete list, see the manual page for the erlang module. 21 20 21 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Built-in Functions •Built-in functions can modify the real time properties of the system •A process executing a BIF will not be suspended until the BIF has completed executing •Other processes will thus not be allowed to execute on the same scheduler •Use BIFs with care! 22 Use BIFs with care! © 1999-2011 Erlang Solutions Ltd. Built-in Functions: examples 1> date(). {2010,9,25} 2> atom_to_list(abcd). "abcd" 3> tuple_to_list(list_to_tuple([1,2,3,4])). [1,2,3,4] 4> length([1,2,3,4,5]). 5 23 22 23 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. apply(Module, Function, Arguments) M:function(Args) M:F(Args) Built-in Functions: meta calls • apply/3 is a BIF used to dynamically evaluate functions • The function must be exported • The arguments can possibly be an empty list •All the arguments can be established at runtime • Extremely powerful when implementing generic code 24 © 1999-2011 Erlang Solutions Ltd. Built-in Functions: meta calls 1> Module = io. io 2> Function = format. format 3> Arguments = ["Hello World~n", []]. ["Hello World~n",[]] 4> apply(Module, Function, Arguments). Hello World ok 8> io:Function("Hello World ",[]). Hello World ok 9> Module:Function("Hello World ", []). Hello World ok 25 The arguments to apply could have been evaluated during runtime The arities of the M:func(Args) and M:F(Args) forms are static 24 25 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Libraries io.erl generalised input/output functionality file.erl generalised interface towards the file system lists.erl standard list processing functions code.erl functionality to load, test and manipulate code. math.erl mathematical functions 26 © 1999-2011 Erlang Solutions Ltd. Libraries • Erlang has a set of libraries where functionality useful to the software designer has been placed •The previous list of modules are all part of the standard Erlang/OTP distribution •Many more libraries and modules are available: - They are referenced in the official documentation 27 26 27 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. lists:append(List1, List2) -> NewList. lists:delete(Element, List) -> NewList. lists:last(List) -> Element. lists:reverse(List) -> ReversedList. lists:sort(List) -> SortedList. lists:keysort(Pos, TupleList) -> SortedList. lists:keydelete(Key, Pos, TupleList) -> NewList. lists:keysearch(Key, Pos, TupleList) -> false | {value, Tuple} Libraries • The lists module is the most used and one of the most useful ones 28 © 1999-2011 Erlang Solutions Ltd. Manual Pages In the UNIX shell $ erl -man Module In HTML By accessing file://$ERL_ROOT/doc/index.html In Emacs Picking one of the entries under the Erlang menu In General Manual pages for all the modules can be read online, from the shell, in emacs or in the OTP reference manual. Take a look at the available modules to get an idea of the existing functionality 29 28 29 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. The Debugger •The Erlang debugger is a graphical tool providing mechanisms to debug code and influence program execution - Allows the user to insert break points - Step through the code - Inspect and manipulate variables - Inspecting the recursive stack 30 © 1999-2011 Erlang Solutions Ltd. The Debugger •debugger:start() 31 The windows version is known to be unstable 30 31 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. The Debugger •Interpret the code - Must be compiled with the debug_info flag - use c(Module, [debug_info]) 32 © 1999-2011 Erlang Solutions Ltd. The Debugger •Stepping through the code 33 32 33 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Summary: sequential Erlang II • Sequential Erlang I • Sequential Erlang II - BIFs - Libraries - Manual Pages - The Debugger • Sequential Erlang III 34 © 1999-2011 Erlang Solutions Ltd. Overview: sequential Erlang III • Sequential Erlang I • Sequential Erlang II • Sequential Erlang III - Run Time Errors - Try ... catch - Throw - Catch 35 34 35 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. •function_clause is returned when none of the existing function patterns matchesfactorial(N) when N > 0 -> N * factorial(N - 1); factorial(0) -> 1. Run Time Errors: match 1> math:factorial(-1). ** exception error: no function clause matching math:factorial(-1) 36 © 1999-2011 Erlang Solutions Ltd. •case_clause is returned when none of the existing patterns in the case statement matches test(N) -> case N of -1 -> false; 1 -> true end. Run Time Errors: match 1> test:test(0). ** exception error: no case clause matching 0 in function test:test/1 37 36 37 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. •if_clause is returned when none of the existing expressions in the if statement evaluates to true test(N) -> if N < 0 -> false; N > 0 -> true end. Run Time Errors 1> test:test(0). ** exception error: no true branch found when evaluating an if expression in function test:test/1 38 © 1999-2011 Erlang Solutions Ltd. 1> Tuple = {1, two, 3}. {1,two,3} 2> {1, two, 3, Four} = Tuple. ** exception error: no match of right hand side value {1,two,3} Run Time Errors: match • badmatch errors occur in situations when pattern matching fails and there are no other alternative clauses to choose from. 39 38 39 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. 1> length(helloWorld). ** exception error: bad argument in function length/1 called as length(helloWorld) Run Time Errors: others • badarg is returned when a BIF with wrong arguments is called. 40 © 1999-2011 Erlang Solutions Ltd. 1> test:hello(). ** exception error: undefined function test:hello/0 Run Time Errors: others • undef will be returned if the global function being called is not defined or exported 41 40 41 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. 1> 1+a. ** exception error: bad argument in an arithmetic expression in operator +/2 called as 1 + a Run Time Errors: others • badarith is returned when arithmetical operations are executed with values that are neither integers or floats. 42 © 1999-2011 Erlang Solutions Ltd. try Expression of Pattern1 [when Guard1] -> ExpressionBody1; Pattern2 [when Guard2] -> ExpressionBody2 catch [Class1:]ExceptionPattern1 [when ExceptionGuardSeq1] -> ExceptionBody1; [Class2:]ExceptionPattern2 [when ExceptionGuardSeq2] -> ExceptionBody2 end Try ... catch •try ... catch provides a mechanism for monitoring the evaluation of an expression •It will trap exits caused by expected run time errors •The patterns Class1: and Class2: can define the type of exception handled •The ExceptionPatterns can restrict the reason why an exception is raised. 43 42 43 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. 1> self(). <0.53.0> 2> X=2, X=3. ** exception error: no match of right hand side value 3 4> self(). <0.57.0> 5> try (X=3) of 5> Val -> {normal, Val} 5> catch 5> _:_ -> 43 5> end. 43 6> self(). <0.57.0> Try ... catch •_:_ allows to match on all errors no matter what they are. •The error is caught and the process doesn't crash 44 © 1999-2011 Erlang Solutions Ltd. 1> X=2. 2 2> try (X=3) of 2> Val -> {normal, Val} 2> catch 2> error:Error -> {error, Error} 2> end. {error,{badmatch,3}} 3> try (X=3) of 3> Val -> {normal, Val} 3> catch 3> error:{badmatch,_} -> 42 3> end. 42 Try ... catch •The error:Error pattern allows to bind the error reason to a variable and match on it •error:{badmatch,_} allows to match only errors caused by erroneous pattern matching 45 44 45 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. throw() Throw •throw is used for non- local returns in deep recursive function calls. •The execution flow jumps to the first catch in the execution stack •Useful for handling exceptions in deeply nested code when you do not want to handle possible errors. 46 WARNING!! use with care as it makes the code hard to debug and understand © 1999-2011 Erlang Solutions Ltd. add(X, Y) -> test(Y), test(X), X + Y. test(X) when is_integer(X) -> ok; test(X) -> throw({error, {non_integer, X}}). 1> math:add(1, one). ** exception throw: {error,{non_integer,one}} 2> try math:add(1, one) of 2> _ -> ok 2> catch 2> Class:Reason -> {Class, Reason} 2> end. {throw,{error,{non_integer,one}}} Throw 47 46 47 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Try ... catch: examples -module(exception). -export([try_wildcard/1]). try_wildcard(X) when is_integer(X) -> try return_error(X) catch throw:Throw -> {throw, Throw}; error:_ -> error; Type:Error -> {Type, Error}; _ -> other; %% Will never be returned _:_ -> other %% Will never be returned end. 48 © 1999-2011 Erlang Solutions Ltd. Try ... catch: examples return_error(X) when X < 0 -> throw({'EXIT',{badarith,[{exception,return_error,1}, {erl_eval,do_apply,5}, {shell,exprs,6}, {shell,eval_exprs,6}, {shell,eval_loop,3}]}}); return_error(X) when X == 0 -> 1/X; return_error(X) when X > 0 -> {'EXIT',{badarith,[{exception,return_error,1}, {erl_eval,do_apply,5}, {shell,exprs,6}, {shell,eval_exprs,6}, {shell,eval_loop,3}]}}. 49 48 49 Tuesday, 6 September 2011 © 1999-2011 Erlang Solutions Ltd. Try ... catch: examples 1> exception:try_wildcard(-1). {throw,{'EXIT',{badarith,[{exception,return_error,1}, {erl_eval,do_apply,5}, {shell,exprs,6}, {shell,eval_exprs,6}, {shell,eval_loop,3}]}}} 2> exception:try_wildcard(0). error 3> exception:try_wildcard(1). {'EXIT',{badarith,[{exception,return_error,1}, {erl_eval,do_apply,5}, ... {shell,eval_loop,3}]}} 50 © 1999-2011 Erlang Solutions Ltd. catch Catch • catch provides a mechanism for monitoring the evaluation of an expression • It will trap
本文档为【Sequential Erlang】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_486436
暂无简介~
格式:pdf
大小:516KB
软件:PDF阅读器
页数:16
分类:互联网
上传时间:2012-10-03
浏览量:7