- 斐波那契数列实现
-module(fibonacci2).
-include_lib("eunit/include/eunit.hrl").
-export([fibo/1]).
fibo(N) -> check(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]),
?_assertEqual(false, fibo(9.0)),
?_assertEqual(false, fibo(-9)),
?_assertEqual(false, fibo(a))
].
运行实例:
测试实例:
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].
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))
].
运行实例:
测试实例: