erlang 运算符

erlang 运算符

hello world,erlang is good! 

Eshell V5.9.3.1  (abort with ^G)
1> 1 == 1.0 .
true
2> 1 =:= 1.0 .
false
3> 1 /= 1.0 .
false
4> 1 =/= 1.0 .
true
5> (0 == 0) or (1/0 > 2).
** exception error: an error occurred when evaluating an arithmetic expression
     in operator  '/'/2
        called as 1 / 0
6> (0 == 0) orelse (1/0 > 2).
true
7> true or ok.
** exception error: bad argument
     in operator  or/2
        called as true or ok
8> true orelse ok.
true
9> true and ok.   
** exception error: bad argument
     in operator  and/2
        called as true and ok
10> true andalso ok.
ok
11> 
11> true andalso ok andalso false.
** exception error: bad argument: ok
12> true andalso true andalso ok.   
ok
13> 1 div 2.
0
14> 1 rem 2.
1
15> 1/1.
1.0
16> not(1>2).
true
17> 11 xor 10.
** exception error: bad argument
     in operator  xor/2
        called as 11 xor 10
18> true xor true.
false
19> 2#11 bor 2#10.
3
20> 2#11 band 2#10.
2
21> 2#11 bxor 2#10.
1
22> bnot 2#10.
-3
23> 2#10 bsl 1.
4
24> 2#10bsr 1.
1
25> 

下面参考自:没有开花的树
Erlang的比较运算符
写法如下:
Expr1 op Expr2
1> 1 == 1.
true
op Description
== 等于
/= 不等于
=< 小于或等于
< 小于
>= 大于或等于
> 大于
=:= 恒等于
=/= 恒不等于
以=:=和==为例,说明恒等于和等于的区别:
2> 1 == 1.0.
true
3> 1 =:= 1.0.
false
不同类型比较会有什么结果?
针对不同数据类型比较,如下:
number < atom < reference < fun < port < pid < tuple < list < bit string
就是说,[] > 0结果是true

Erlang的数学运算符
有两种写法,如下:
op Expr
Expr1 op Expr2
4> + 1.
1
5> 1 + 1.
2
op Description Argument type
+ 一元 + number
- 一元 - number
+ 加法 number
-
减法
number
*
乘法
number
/ 浮点除法 number
div
整数除法
integer
bnot 一元 not 位运算 integer
rem 整数求余 integer
band 与运算 integer
bor 或运算 integer
bxor 异或运算 integer
bsl 左移运算 integer
bsr 右移运算 integer

例子如下:

6> +1.
1
7> -1.
-1
8> 1+1.
2
9> 4/2.
2.0
10> 5 div 2.
2
11> 5 rem 2.
1
12> 2#10 band 2#01.
0
13> 2#10 bor 2#01.
3
14> 8 bsr 1.
4
15> 8 bsl 1.
16

Erlang的布尔运算符
写法如下:
op Expr
Expr1 op Expr2
op Description
not 一元逻辑非
and 逻辑与
or 逻辑或
xor 逻辑异或
例子:
16> not true.
false
17> true and false.
false
18> true xor false.
true
另外,还有两个布尔运算符 orelse 和 andalso,这两个用于短路运算,写法如下:
Expr1 orelse Expr2
Expr1 andalso Expr2

什么是短路运算?

例子:

Expr1 and Expr2

Expr1 andalso Expr2

对于and运算,如果Expr1为假,还会继续执行Expr2,然后再判定表达式为假;而andalso运算,当Expr1为假就判定表达式为假,不再执行Expr2,所以这里andalso效率比较高。



参考:
http://blog.youkuaiyun.com/zhongruixian/article/details/42554019



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值