变量shell
变量必须以大写字母开头。在erlang里,变量就像数学里的那样。当关联一个值与变量时,所下的是一种断言,也就是事实的陈述。这个变量就是那个值,仅此而已。编程
对X=1234这个简单语句所带有的两种假设。ide
首先, X不是一个变量,不是你习惯的Java和C等语言里的概念this
其次,=不是一个赋值操做符,而是一个模式匹配操做符。spa
This behavior of the =
operator is the basis of something called 'Pattern matching',rest
What this operator does when mixed with variables is that if the left-hand side term is a variable and it is unbound (has no value associated to it), Erlang will automatically bind the right-hand side value to the variable on the left-hand side. The comparison will consequently succeed and the variable will keep the value in memory.
code
即对于 “Lhs = Rhs”这样一个式子。其先对Rhs求值,再将其结果与左端Lhs进行模式匹对。
ci
在erlang里,变量得到值是一次成功模式匹配的操做结果。字符串
Technically, variables can start with an underscore ('_') too, but by convention their use is restricted to values you do not care about, yet you felt it was necessary to document what it contains.underscore
You can also have variables that are only an underscore:
2> _ = 1+3. 4 3> _. * 1: variable '_' is unbound
The _ variable is always seen as unbound and acts as a wildcard for pattern matching.
变量“_”是不绑定的,既没有值, 在模式匹配中能够做为通配符使用。
2、 原子
在erlang里,原子被用于表示常量。至关于C语言中的宏定义。原子以小写字母开头,后接一个串字母,数字,下划线(_ )或者@,若是不是以小写字母开头,或是小写字母以外的符号开头,原子能够放在单引号(' )内。如'Monday','_name'等。
在某些语言里,单引号和双引号能够互换使用。Erlang里不是这样的。单引号的用法如上面所说,双引号用于给字符串字面量(string literal)定界。
3、 元组
若是想把一些数量固定的项目归组成单一的实体,就会使用元组(tuple)。建立元组的方法是用大括号{}把想要表示的值括起来,并用逗号分隔它们。
为了容易记住元组的用途,一种经常使用的作法是将原子做为元组的第一个元素,用它来表示元组是什么。这种给元组贴标签的方式不是语言所要求的,而是一种推荐的编程风格。
看看下面的例子,每一个语句分别表明了什么意思?为何有的时候匹配不成功?
1> P = {10 , 5}. %%给变量P绑定一个元组 {10,5} 2> P = { point, 10, 5}. %%再次给P赋值,则是匹配不成功,变量得到值是一次成功模式匹配的操做结果。 ** exception error: no match of right hand side value {point,10,5} 3> P1 = {point, 10, 5}. %%使用令一个变量还绑定元组 {point,10,5} 4> {point1, X, Y} = P1. %%不匹配的缘由是由于point1和 point是不一样的原子。原子表示的是常量。 ** exception error: no match of right hand side value {point,10,5} 5> {point, X, Y} = P1. %%匹配成功,变量X,Y分别绑定十、5 {point,10,5} 6> X. 10 7> Y. 5 8> X= 20. %%再次给X绑定值则不成功,由于变量X绑定了值了。 ** exception error: no match of right hand side value 20
明白了上面的例子,就简单的理解了在Erlang里变量,原子,元组的基本的概念。
这个连接讲数据类型等讲的的超好:http://learnyousomeerlang.com/starting-out-for-real