一、代码
1.1 3种条件判断方法
1. 通过函数参数模式匹配,来判断应该执行哪个函数。
2. 通过case模式匹配,来判断应该执行哪些语句。
3. 通过if,来判断应该执行哪些语句。
特别注意:函数、case是模式匹配,if是判断表达式的值是否为true。
1.2 代码
-module(test).
-export([listlen/1]).
%1. 通过函数参数模式匹配,来判断应该执行哪个函数
%listlen([]) -> 0;
%listlen([_|Xs]) -> 1 + listlen(Xs).
%2. 通过case模式匹配,来判断应该执行哪些语句
%listlen(Y) ->
% case Y of
% [] -> 0;
% [_|Xs] -> 1 + listlen(Xs)
% end.
%3. 通过if,来判断应该执行哪些语句
listlen(Y) ->
if
Y == [] -> 0;
%Y /= [] -> 1 + listlen(tl(Y))
%Y /= [] -> 1 + listlen(lists:nthtail(1, Y))
Y /= [] -> [_|Xs] = Y, 1 + listlen(Xs)
end.
二、输出结果