博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

erlang 编程指南 第三章-顺序编程 课后练习

Posted on 2013-06-29 21:35  bobolive  阅读(224)  评论(0编辑  收藏  举报

1. sum(3) => 6; sum(1,3) => 6; sum(6,6) => 6;

sum(N) when is_integer(N) -> sum_acc(N,0);
sum(_) -> {error, {bad_argument}}.

sum_acc(0, Sum) -> Sum;
sum_acc(N, Sum) -> sum_acc(N-1, Sum + N).

sum(N, M) when is_integer(N), is_integer(M), M >= N -> sum_acc3(N, M, 0);
sum(_, _) -> {error, {bad_argument}}.

sum_acc3(N, N, Sum) -> Sum + N;
sum_acc3(N, M, Sum) -> sum_acc3(N, M-1, Sum+M).

2. creat(3) => [1,2,3];

creat(N) when N > 0 -> creat_acc(N, []);
creat(_) -> {error, {bad_argument}}.

creat_acc(0, List) -> List;
creat_acc(N, List) -> creat_acc(N-1, [N | List]).

3. 打印 1~N 的整数

print(N) when is_integer(N), N > 0 -> print_acc(N,0);
print(_) -> {error, {bad_argument}}.

print_acc(0,List) -> io:format("Numer:~p~n", [List]);
print_acc(N,List) -> print_acc(N-1,[N|List]).

 

3-5 列表操作

filter(List, N) when is_list(List) -> filter_acc(List, N, []); 
filter(_, N) -> {error, {bad_argument}}.

filter_acc([], N, List)  -> onelist(List);
filter_acc([H|T], N, List) when H =< N ->  filter_acc(T, N, [onelist(List)|H]);
filter_acc([H|T], N, List) when H > N ->  filter_acc(T, N, List).

onelist([]) -> [];
onelist([H|T]) when is_list(H) ->  H ++ onelist(T);
onelist([H|T]) when not is_list(H) -> onelist(H) ++ onelist(T);
onelist(H) -> [H].

erlang 中的 ++ 是很耗性能的,这在erlang 编程指南中有明确指出, 而且onlist 对于头部是复杂列表(非结构良好列表)时什么报错比如
[[[[[[[]|1]|2]|3]|5]|6]|7] ++ [8] 就会报错,++ 号两边列表结构不对等, 下面优化下。

filter(List, N) when is_list(List) -> filter_acc(List, N, []); 
filter(_, N) -> {error, {bad_argument}}.

filter_acc([], N, List)  -> io:format("List : ~p | ~p~n", [List, concat(List)]), concat(List);
filter_acc([H|T], N, List) when H =< N ->  filter_acc(T, N, [List|H]);
filter_acc([H|T], N, List) when H > N ->  filter_acc(T, N, List).

concat([H|[]]) -> [H];
concat([[]|T]) -> [T];
concat([H|T]) -> lists:concat([concat_cc(H) , concat_cc(T)]).
concat_cc(N) when is_list(N) -> concat(N); concat_cc(N) -> [N].