zoukankan      html  css  js  c++  java
  • 【erlang ~ 4 days】 Day # 1.2 Sequential Programming

    Sequential Programming

    出处: http://www.erlang.org/course/sequential_programming.html

    1. 数字

      erlang下数字有两种,整型 和 浮点型

      a 整型

        10        %%正整数字
        -234       %%
        16#AB10F     %%16进制整数
        2#110111010  %%2进制整数 【最多36】
        $A         %% 字符A的ascii码

      b 浮点型

        17.368
        -56.654
        12.34E-10

    2 Atoms 

      abcef
      start_with_a_lower_case_letter
      'Blanks can be quoted'
      'Anything inside quotes \n\012'

      暂时还不理解atoms的含义,常量?还是?

    3. tuples (元组) 

      {123, bcd}
      {123, def, abc}
      {person, 'Joe', 'Armstrong'}
      {abc, {def, 123}, jkl}
      {}

    4. Lists (列表)

      [123, xyz]
      [123, def, abc]
      [

      {person, 'Joe', 'Armstrong'},
      {person, 'Robert', 'Virding'},
      {person, 'Mike', 'Williams'}
      ]
      "abcdefghi" becomes  [97,98,99,100,101,102,103,104,105]
          "" becomes  []

      1. 列表存储一组长度可变的items

      2. 双引号之间的字符串的每个字符中的ascii码会被插入到列表中

    5. Variables (变量)

      Abc
      A_long_variable_name
      AnObjectOrientatedVariableName

      1. 大写字母开头

      2. no "funny characters"

      3. 变量只能赋值一次,(Variables can be only bound once)

    6.  Complex data structures(复杂数据结构)

      [{

      {person,'Joe', 'Armstrong'},
      {telephoneNumber, [3,5,9,7]},
      {shoeSize, 42},
      {pets, [{cat, tubby},{cat, tiger}]},
      {children,[{thomas, 5},{claire,1}]}},
      {{person,'Mike','Williams'},
      {shoeSize,41},
      {likes,[boats, beer]},
      ...

      元组,list,已经绑定了值的变量,整型,atoms,浮点型可以任意嵌套

    7. Pattern Matching

      A = 10
      Succeeds - binds A to 10

      {B, C, D} = {10, foo, bar}
      Succeeds - binds B to 10, C to foo and D to bar

      {A, A, B} = {abc, abc, foo}
      Succeeds - binds A to abc, B to foo

      {A, A, B} = {abc, def, 123}
      Fails

      [A,B,C] = [1,2,3]
      Succeeds - binds A to 1, B to 2, C to 3

      [A,B,C,D] = [1,2,3]
      Fails

      【可能说的不准确】等号不是赋值~~~ 等号是对左右两侧做‘匹配’,如果能够匹配上,则将右侧对应的值绑定到左侧~~

    8. Pattern Matching (Cont)

      [A,B|C] = [1,2,3,4,5,6,7]
      Succeeds - binds A = 1, B = 2,C = [3,4,5,6,7]

      [H|T] = [1,2,3,4]
      Succeeds - binds H = 1, T = [2,3,4]

      [H|T] = [abc]
      Succeeds - binds H = abc, T = []

      [H|T] = []
      Fails

      {A,_, [B|_],{B}} = {abc,23,[22,x],{22}}
      Succeeds - binds A = abc, B = 22
      

      Note the use of "_", the anonymous (don't care) variable.

    9.  Function Calls(函数调用)

      module:func(Arg1, Arg2, ... Argn)
      func(Arg1, Arg2, .. Argn)


      Arg1 .. Argn are any Erlang data structures.

      ---

      Arg1 .. Arg2 可以是任何数据结构,1~6

      The function and module names (func and module in the above) must be atoms.

      ---

      函数名和模块名必须是atoms


      A function can have zero arguments. (e.g. date() - returns the current date).

      ---

      函数的参数数量可以是0个


      Functions are defined within Modules.

      ---

      函数在模块中定义


      Functions must be exported before they can be called from outside the module where they are defined.

      ---

      模块中定义的函数,必须先export才能被外部调用 ~~ 【某种封装?】

    10. Module System

      -module(demo).
      -export([double/1]).

      double(X) ->
      times(X, 2).

      times(X, N) ->
      X * N.
      

      double can be called from outside the module, times is local to the module.

      ---

      double 因为做了export声明,所以可以被外部引用

      double/1 means the function double with one argument (Note that double/1 and double/2 are two different functions).

      ---

      double/1 表示需要1个参数的double函数【类似重载,同名函数使用不同数量,类型的参数区分,erlang里是不同的参数数量】

    11. Starting the system

      unix> erl
      Eshell V2.0
      1> c(demo).
      double/1 times/2 module_info/0
      compilation_succeeded
      2> demo:double(25).
      50
      3> demo:times(4,3).
      ** undefined function:demo:times[4,3] **
      ** exited: {undef,{demo,times,[4,3]}} **
      4> 10 + 25.
      35
      5>


      c(File) compiles the file File.erl.

      ---

      c(File)操作编译File.erl源文件


      1> , 2> ... are the shell prompts.

      ---

      1>, 2> ... 是shell提示符


      The shell sits in a read-eval-print loop.

      ---

      【额,不明白,不过貌似不重要】

    12. Building In functions(BIFs) 内嵌函数

      date()
      time()
      length([1,2,3,4,5])
      size({a,b,c})
      atom_to_list(an_atom)
      list_to_tuple([1,2,3,4])
      integer_to_list(2234)
      tuple_to_list({})
      

      Are in the module erlang.

      ---

      在名为erlang的模块中【难道默认就使用了c(erlang)?】
      

      Do what you cannot do (or is difficult to do) in Erlang.
      Modify the behaviour of the system.
      Described in the BIFs manual.

      ---

      【trivial】

    13. Function Syntax 【函数语法】

      Function Is defined as a collection of clauses.
      func(Pattern1, Pattern2, ...) ->
      ... ;
      func(Pattern1, Pattern2, ...) ->
      ... ;
      ...
      func(Pattern1, Pattern2, ...) ->
      ... .
      Evaluation Rules
      Clauses are scanned sequentially until a match is found.

      ---

      【函数调用的时候,会遍历定义,如果入参和某个clause匹配,就会执行】


      When a match is found all variables occurring in the head become bound.
      Variables are local to each clause, and are allocated and deallocated automatically.

      ---

      函数变量在局部有效,资源自动回收


      The body is evaluated sequentially.

    14. Functions(Cont)  

      -module(mathStuff).
      -export([factorial/1, area/1]).

      factorial(0) -> 1;
      factorial(N) -> N * factorial(N-1).

      area({square, Side}) ->
        Side * Side;
      area({circle, Radius}) ->
        % almost :-)
        3 * Radius * Radius;
      area({triangle, A, B, C}) ->
        S = (A + B + C)/2,
        math:sqrt(S*(S-A)*(S-B)*(S-C));
      area(Other) ->
        {invalid_object, Other}.

    15. Evaluation Example

      factorial(0) -> 1;
      factorial(N) ->
        N * factorial(N-1).

      > factorial(3)
      matches N = 3 in clause 2
      == 3 * factorial(3 - 1)
      == 3 * factorial(2)
      matches N =2 in clause 2
      == 3 * 2 * factorial(2 - 1)
      == 3 * 2 * factorial(1)
      matches N = 1 in clause 2
      == 3 * 2 * 1 * factorial(1 - 1)
      == 3 * 2 * 1 �* factorial(0)
      == 3 * 2 * 1 �* 1 (clause 1)
      == 6

    16. Guarded Function Clauses

      factorial(0) -> 1;
      factorial(N) when N > 0 ->
        N * factorial(N - 1).

      The reserved word when introduces a guard.
      Fully guarded clauses can be re-ordered.

      factorial(N) when N > 0 ->
      N * factorial(N - 1);
      factorial(0) -> 1.


      This is NOT the same as:

      factorial(N) ->
      N * factorial(N - 1);
      factorial(0) -> 1.
      (incorrect!!) 【错误的,回导致死循环】

    17. Examples of guards

      number(X) - X is a number
      integer(X) - X is an integer
      float(X) - X is a float
      atom(X) - X is an atom
      tuple(X) - X is a tuple
      list(X) - X is a list

      length(X) == 3 - X is a list of length 3
      size(X) == 2 - X is a tuple of size 2.

      X > Y + Z - X is > Y + Z
      X == Y - X is equal to Y
      X =:= Y - X is exactly equal to Y
      (i.e. 1 == 1.0 succeeds but
      1 =:= 1.0 fails)


      All variables in a guard must be bound.
      See the User Guide for a full list of guards and allowed function calls.

    18. Traversing Lists [遍历列表]

      average(X) -> sum(X) / len(X).

      sum([H|T]) -> H + sum(T);
      sum([]) -> 0.

      len([_|T]) -> 1 + len(T);
      len([]) -> 0.

      Note the pattern of recursion is the same in both cases. This pattern is very common.
      Two other common patterns:
      

      double([H|T]) -> [2*H|double(T)];
      double([]) -> [].

      member(H, [H|_]) -> true;
      member(H, [_|T]) -> member(H, T);
      member(_, []) -> false.

    19. Lists and Accumulators

      average(X) -> average(X, 0, 0).

      average([H|T], Length, Sum) ->
        average(T, Length + 1, Sum + H);
      average([], Length, Sum) ->
        Sum / Length.


      Only traverses the list ONCE
      Executes in constant space (tail recursive)
      The variables Length and Sum play the role of accumulators
      N.B. average([]) is not defined - (you cannot have the average of zero elements) - evaluating average([]) would cause a run-time error - we discuss what happens when   run time errors occur in the section on error handling .

    20. shell commands

     

      h() - history . Print the last 20 commands.

      b() - bindings. See all variable bindings.

      f() - forget. Forget all variable bindings.

      f(Var) - forget. Forget the binding of variable
      X. This can ONLY be used as a command to
      the shell - NOT in the body of a function!

      e(n) - evaluate. Evaluate the n:th command
      in history.

      e(-1) - Evaluate the previous command.


      Edit the command line as in Emacs
      See the User Guide for more details and examples of use of the shell.

    21. special functions

      apply(Mod, Func, Args)


      Apply the function Func in the module Mod to the arguments in the list Args.
      Mod and Func must be atoms (or expressions which evaluate to atoms).
      

      1> apply( lists1,min_max,[[4,1,7,3,9,10]]).
      {1, 10}

      Any Erlang expression can be used in the arguments to apply.

    22. Special forms

      case lists:

      member(a, X) of
      true ->
      ... ;
      false ->
      ...
      end,
      ...

      if
      integer(X) -> ... ;
      tuple(X) -> ...
      end,
      ...
      

      Not really needed - but useful.

      

    【通读了一遍erlang官网的4天教程的第一课,做个记录】

     感觉与以前接触的语言有很大的区别,挺晕的不同,主要是是一些基础概念:

    1. 赋值,erlang难道没有赋值这个概念,而是binding~~~~

    2. 函数的定义和调用方式,逻辑更加清晰,感觉有点重载的感觉~~~

    3. 模块的引用,erlang里貌似没有public,private之类的概念,而是将公开的调用export出去,由模块自己控制哪儿些对外可见~~~~

    准备第二节~~~

    喜欢一起简单,实用的东西,拒绝复杂花哨,我不是GEEK.
  • 相关阅读:
    ubuntu修改主机名称+修改终端显示目录和计算机名称
    google 搜索 PPT
    就为在YouTube上下载个视频
    读书笔记 ---- 《嵌入式系统技术》
    WARNING: Unable to open an initial console
    Ubuntu ftp服务器搭建 + UltraEdit编辑FTP文件
    51Nod 1079 中国剩余定理【模板题】
    Leetcode 11 Container with most water【双指针】
    kuangbin专题六 最小生成树【从入门到熟练】【5题】
    kuangbin专题十二 基础DP1【从入门到熟练】【10题】
  • 原文地址:https://www.cnblogs.com/igloo1986/p/3059362.html
Copyright © 2011-2022 走看看