zoukankan      html  css  js  c++  java
  • erlang 编程指南 第三章-顺序编程 课后练习

    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].
  • 相关阅读:
    arguments伪对象数组 javascript
    typeof获取变量的数据类型 javascript
    《转》Cucumber之一Cucumber概述——学习新篇章
    【转】Dubbo分布式服务框架
    SQL语句
    (转)面试必备之乐观锁与悲观锁
    多线程的实现方式
    Exception和RuntimeException区别
    实例化对象的两种方式
    包装类对象的比较
  • 原文地址:https://www.cnblogs.com/bobolive/p/3162816.html
Copyright © 2011-2022 走看看