Erlang notes[2]

发布于:2025-08-16 ⋅ 阅读:(17) ⋅ 点赞:(0)

standard modules

  1. as similar as other popular programming language,Erlang also has itself standard modules to help programmer finish regular works.
  2. the io module can be able to serve programmer to write some formatted input/output.if you has any question,the h(module name) command will be your relaible assistant.
  3. the format function take two lists as parameters,the first one is the formatted string,and the second one will be fill in these format symbols which are insided the firt list such as ~w ~w.for example:
io:format("it is so cool~n", []).
io:format("nice to ~w ~w~n", [meet , you]).

Matching, Guards, and Scope of Variables

  1. the when sentence will be executed immediately as long as it’s following conditions are satisfied.
    for example,this erlang program count the number of odd number in the list.
-module(hello).
-export([list_amount/1]).
%the list_amount function can get the number of odd number in a list.

list_amount(Num_List) ->
   list_amount(Num_List,0).
list_amount([], Sum_result) ->
    Sum_result;
list_amount([Head|Rest], Sum_result) when Head rem 2 =:= 1;Head rem 2 =:= -1 ->
    list_amount(Rest,Sum_result+1),io:format("~w ~n",[Head]);
list_amount([Head|Rest], Sum_result)  when Head rem 2 =:= 0 ->
    list_amount(Rest,Sum_result).
25> c(hello).
{ok,hello}
26> hello:list_amount([11,33,53,22]).
53
33
11
ok
27> hello:list_amount([11,33,53,22,-23]).
-23
53
33
11
ok
28> hello:list_amount([11,33,53,22,-23,-102]).
-23
53
33
11
ok
29>

the above example illustrates how to apply the when ,which actually is guard,when the guard is true, the following code will be run.
there are a lot of useful operators can be used in guards as follows.

< less than
> greater than
== equal
>= greater or equal
=< less or equal
/= not equal

references

  1. https://www.erlang.org/doc/

网站公告

今日签到

点亮在社区的每一天
去签到