Erlang实现斐波、快排、冒泡及EUnit测试用例

  1. 斐波那契数列实现
-module(fibonacci2).

-include_lib("eunit/include/eunit.hrl").

-export([fibo/1]).

fibo(N) -> check(N).
%fibo(N) -> fb(1, [0], 0, N).

check(N) ->
  if
    N < 0 -> false;
	is_integer(N) -> fb(1, [0], 0, N);
	true -> false
end.

fb(A, [B|Acc], I, N) when I == N -> reverse([B|Acc], []);
fb(A, [B|Acc], I, N) when I < N -> fb(A+B, [A|[B|Acc]], I+1, N).

reverse([], Acc) -> Acc;
reverse([H|T], Acc) -> reverse(T, [H|Acc]).

%%-------------------------------------
%% 				测试用例
%%-------------------------------------
fibo_test_() ->
[?_assert(fibo(0) =:= [0]),
?_assert(fibo(5) =:= [0,1,1,2,3,5]),
?_assert(fibo(9) =:= [0,1,1,2,3,5,8,13,21,34]),
%?_assertException(error, function_clause, fibo(9.0)),
%?_assertException(error, function_clause, fibo(-9)),
%?_assertException(error, function_clause, fibo(a))
?_assertEqual(false, fibo(9.0)),
?_assertEqual(false, fibo(-9)),
?_assertEqual(false, fibo(a))
].

运行实例:
Erlang实现斐波、快排、冒泡及EUnit测试用例_第1张图片
测试实例:
在这里插入图片描述
2.快速排序实现

-module(quick_sort2).

-include_lib("eunit/include/eunit.hrl").

-export([qs/1]).

qs(Acc) -> qsort(Acc).

qsort([]) -> [];
qsort([H|T]) -> 
  qsort([ X || X <- T, X =< H])
  ++ [H] ++
  qsort([ X || X <- T, X > H]).
  
%%--------------------------------------------
%%                  测试用例
%%--------------------------------------------
qs_test_() ->
[
?_assert(qs([5,7,3,2,6,1,9,0]) =:= [0,1,2,3,5,6,7,9]),
?_assert(qs([0,0,0]) =:= [0,0,0]),
?_assert(qs([]) =:= []),
?_assert(qs([2,3,77,5,3,1]) =:= [1,2,3,3,5,77]),
?_assert(qs([3,2.0,5.3,3.6,8.1]) =:= [2.0,3,3.6,5.3,8.1]),
?_assert(qs([2,-5,-15,1,0]) =:= [-15,-5,0,1,2]),
?_assert(qs([a, b, a, c]) =:= [a,a,b,c]),
?_assertException(error, function_clause, qs({2,7,3,5.2,1})),
?_assertException(error, function_clause, qs(234))
].

运行实例:
在这里插入图片描述
测试实例:
在这里插入图片描述
3.冒泡排序实现

-module(bubble_sort2).

-include_lib("eunit/include/eunit.hrl").

-export([bsort/1]).

bsort(Acc) -> boutsort(Acc, length(Acc)).

%% 冒泡外层循环
boutsort(Acc, 0) -> Acc;
boutsort(Acc, N) -> boutsort(binnersort(Acc), N-1).

%%冒泡内层循环(从小到大排序)
binnersort([A, B|Rest]) when A < B ->
  [A | binnersort([B | Rest])];
binnersort([A, B|Rest]) ->
  [B | binnersort([A | Rest])];
binnersort([Lastone]) ->
  [Lastone].							%% lastone必须要大写
  
%%--------------------------------------------
%%                  测试用例
%%--------------------------------------------
bsort_test_() ->
[
?_assert(bsort([5,7,3,2,6,1,9,0]) =:= [0,1,2,3,5,6,7,9]),
?_assert(bsort([0,0,0]) =:= [0,0,0]),
?_assert(bsort([]) =:= []),
?_assert(bsort([2,3,77,5,3,1]) =:= [1,2,3,3,5,77]),
?_assert(bsort([3,2.0,5.3,3.6,8.1]) =:= [2.0,3,3.6,5.3,8.1]),
?_assert(bsort([2,-5,-15,1,0]) =:= [-15,-5,0,1,2]),
?_assert(bsort([a, b, a, c]) =:= [a,a,b,c]),
?_assertException(error, badarg, bsort({2,7,3,5.2,1})),
?_assertException(error, badarg, bsort(234))
].
                           

运行实例:
Erlang实现斐波、快排、冒泡及EUnit测试用例_第2张图片
测试实例:
Erlang实现斐波、快排、冒泡及EUnit测试用例_第3张图片

你可能感兴趣的:(Erlang,erlang,测试用例,开发语言,算法)