今天修改代码时,碰到一个问题,一段很简单的if语句块 就是编译报错!
下面是代码:
%% test2(L)->
%%
%% if string:len(L)>4 ->"222";
%%
%% true ->"111"
%%
%% end.
此时,报错:illegal guard expression。
why??
我又试了其他几种类似的写法:
test1(L)->
A = string:len(L),
if A>4 ->"222";
true ->"111"
end.
test3(L)->
if length(L)>4 ->"222";
true ->"111"
end.
test4(L)->
case string:len(L)>4 of
true ->"111";
_->"222"
end.
又重新翻开书看了看
写着:关卡不能调用用户定义的函数,因为要确保它们没有副作用并能正常结束。
只能调用关卡判断函数和bif内置函数。
注意:上面关卡可能翻译不准确,这是第二版翻译的,第一版称为断言(guard)。多数erlang程序员应该认为是guard,断言应该还算准确。