EUnit例子
(本节内容是对Programming Erlang Chapter19的学习与整理)
模块serial提供了两个函数treeToList/1和listToTree/1对二叉树进行序列化和反序列化,代码如下:
-module(serial).
-export([treeToList/1, listToTree/1]).
treeToList({leaf, N}) ->
[2, N];
treeToList({node, T1, T2}) ->
TTL1 = treeToList(T1),
[Size1|_] = TTL1,
TTL2 = treeToList(T2),
[Size2|_] = TTL2,
[Size1+Size2+1|TTL1++TTL2].
listToTree([2,N]) ->
{leaf, N};
listToTree([_|Code]) ->
case Code of
[M|_] ->
{Code1, Code2} = lists:split(M, Code),
{node,
listToTree(Code1),
listToTree(Code2)
}
end.
测试代码放在serial_tests.erl中,代码如下:
-module(serial_tests).
-export([]).
-import(serial,
[listToTree/1, treeToList/1]).
-include_lib("eunit/include/eunit.hrl").
tree0() ->
{leaf, ant}.
tree1() ->
{node,
{node,
{leaf, cat},
{node,
{leaf, dog},
{leaf, emu}
}
},
{leaf, fish}
}.
leaf_test() ->
?assertEqual(tree0(), listToTree(treeToList(tree0()))).
node_test() ->
?assertEqual(tree1(), listToTree(treeToList(tree1()))).
编译:
> c(serial).
> c(serial_tests).
运行:
> serial_tests:test().
或
> eunit:test(serial_tests).
阅读(1781) | 评论(0) | 转发(0) |