Erlang学习进度情况(四)

来源:互联网 发布:java 获取对象地址 编辑:程序博客网 时间:2024/05/16 06:52

目前发现在Erlang有些特性需要注意,相关内容如下:

第一个就是Short-Circuit Boolean Expressions

有两种语法结构如下:

Expr1 orelse Expr2

表示:This first evaluates Expr1. if Expr1 evaluates to true, Expr2 is not evaluated. If Expr1 evaluates to false, Expr2 is evaluated.

Expr1 andalso Expr2

表示:This first evaluates Expr1. if Expr1 evaluates to true, Expr2 is evaluated. if Expr1 evaluates to false, Expr2 is not evaluated.

在erlang语言里需要注意,A or B; A and B.两个条件都是要执行的。even if the truth value of the expression can be determined by evaluating only the first expression.


第二个就是Term Comparisons

格式如下:

number<atom<reference<fun<port<pid<tuple<list<binary

上面表示的意思是如下:

This means that, for example, a number(any number) is defined to be smaller than an atom(any atom),

that a tuple is greater than an atom, and so on.

下面时8个比较操作:

X>Y         X is greater than Y.

X<Y         X is less than Y.

X<=Y       X is equal to or less than Y.

X>=Y       X is greater than or equal to Y.

X==Y       X is equal to Y.

X/=Y        X is not equal to Y.

X=:=Y      X is identical to Y.

X=/=Y      X is not identical to Y.

这里有以下几个注意地方:

关于=:=和=/=两个操作符

behave in the following way if their arguments are numbers:

if one argument is a integer and the other is a float, then the integer is converted to a float before the comparison is performed.

if both arguments are integers or if both arguments are floats, then the arguments are used "as is", that is without conversion.


关于==和=:=两个操作符

== is useful only when comparing floats with integers.  =:= is for testing whether two terms are identical.


关于Underscore Variables

There's one more thing to say about variables. The special syntax _VarName is used for a normal variable,not an anonymous variable.

关于这种变量的使用场景有2个地方:

第一种:To name a variable that we don't intend to use.

                 That is, writing open(File,_Mode) makes the program more readable than writing open(File,_).

第二种:For debugging purposes.举例说明如下:

                some_func(X)->

                          {P,Q}=some_other_func(X),

  io:formar("Q = ~p~n",[Q]),

  P.

                  This compiles without an error message.

              Now comment out the format statement:

                   some_func(X)->

                           {P,Q}=some_other_func(X),

                            %%   io:formar("Q = ~p~n",[Q]),

                            P.

                    if we compile this, the compiler will issue a warning that the variable Q is not used.

    if we rewrite the function like this:

                     some_func(X)->

                          {P,_Q}=some_other_func(X),

  io:formar("_Q = ~p~n",[_Q]),

  P.

                      then we can comment out the format statement, and the compiler will not complain.