我一直在努力学习Erlang,但遇到了在函数和case
语句中如何结尾的问题。
在函数或case
语句中,何时使用分号(;
),逗号(,
)或句号?
我一直在努力学习Erlang,但遇到了在函数和case
语句中如何结尾的问题。
在函数或case
语句中,何时使用分号(;
),逗号(,
)或句号?
我喜欢将分号看作是或(OR),逗号看作是并且(AND),句号看作是结束。因此
foo(X) when X > 0; X < 7 ->
Y = X * 2,
case Y of
12 -> bar;
_ -> ook
end;
foo(0) -> zero.
读作
foo(X) when X > 0 *OR* X < 7 ->
Y = X * 2 *AND*
case Y of
12 -> bar *OR*
_ -> ok
end *OR*
foo(0) -> zero *END*
这应该能清楚地说明为什么在 case 的最后一个子句后面没有分号。普通代码行末需要逗号。
case语句或if语句等末尾需要分号。
最后一个case或if语句末尾不需要任何内容。
函数末尾需要句号。
示例(对于随机变量名称表示抱歉,显然这不会做任何事情,但说明了一个观点):
case Something of
ok ->
R = 1, %% comma, end of a line inside a case
T = 2; %% semi colon, end of a case, but not the end of the last
error ->
P = 1, %% comma, end of a line inside a case
M = 2 %% nothing, end of the last case
end. %% period, assuming this is the end of the function, comma if not the end of the function
在模块中,句点用于终止模块属性和函数声明(也称为“形式”)。可以通过记住形式不是表达式(没有返回值)来理解这一点,因此句点表示语句的结尾。
请注意,具有不同参数个数的函数定义被认为是单独的语句,因此每个语句都将以句点结束。
例如,对于hello/0
和hello/1
的函数定义如下:
hello() -> hello_world.
hello(Greeting) -> Greeting.
(请注意,在Erlang shell中,句号用于终止和评估表达式,但这是一个异常情况。)
分号用作子句分隔符,既可用于函数子句,也可用于表达式分支。
例如1,函数子句:
factorial(0) -> 1;
factorial(N) -> N * fac(N-1).
例子2,表达式分支:
if X < 0 -> negative;
X > 0 -> positive;
X == 0 -> zero
end
逗号是表达式分隔符。如果一个逗号跟在一个表达式之后,那么它意味着在该从句中还有另一个表达式。
hello(Greeting, Name) ->
FullGreeting = Greeting ++ ", " ++ Name,
FullGreeting.
X == 0 -> zero
后面加上分号。 - Tommy
X > 0; X < 7
会为假? - Jamie Forrest