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].
  • 相关阅读:
    RIGHT-BICEP单元测试——“二柱子四则运算升级版”
    个人项目之“二柱子四则运算升级版”(续)
    个人项目之 “二柱子四则运算”升级版
    “进度条”博客
    课后实验3--四则运算3
    构建之法阅读笔记01
    第二周学习进度
    四则运算2单元测试
    课后实验2--四则运算2
    课后实验1--四则运算
  • 原文地址:https://www.cnblogs.com/bobolive/p/3162816.html
Copyright © 2011-2022 走看看