1

我正在做一些非常简单的事情:在不使用 BIF 的情况下在 Erlang 中反转列表。

这是我的尝试:

%% -----------------------------------------------------------------------------
%% Reverses the specified list.
%% reverse(List) where:
%%   * List:list() is the list to be reversed.
%% Returns: A new List with the order of its elements reversed.
%% -----------------------------------------------------------------------------
reverse(List) ->
  reverse2(List, []).

%% -----------------------------------------------------------------------------
%% If there are no more elements to move, simply return the List
%% -----------------------------------------------------------------------------
reverse2([], List) -> 
  List;

%% -----------------------------------------------------------------------------
%% Taking the head of the List and placing it as the head of our new List
%% This will result in the first element becoming the last, the 2nd becoming
%% the second last, etc etc.
%% We repeat this until we arrive at the base case above
%% -----------------------------------------------------------------------------
reverse2([H|T], List) ->
  reverse2(T, [H|List]).

现在我相信这是正确的,并且使用随机列表在 shell 上对其进行测试,每次都会给出正确的答案。这是我用来运行 Eunit 测试的代码:

%% -----------------------------------------------------------------------------
%% Tests the reverse list functionality.
%% -----------------------------------------------------------------------------
reverse_test_() -> [
  {"Reverse empty list", ?_test(begin

    % Reverse empty list.
    ?assertEqual([], util:reverse([]))
  end)},
  {"Reverse non-empty list", ?_test(begin

    % Reverse non-empty list.
    ?assertEqual([5, 4, 3, 2, 1], util:reverse([1, 2, 3, 4, 5]))
  end)}
].

这就是运行测试告诉我的,特别是:

error:{assertEqual,[{module,util_test},
              {line,101},
              {expression,"util : reverse ( [ ] )"},
              {expected,[]},
              {value,{ok,[]}}]}
  output:<<"">>

这让我感到困惑,我的函数reverse从不返回任何东西ok,在终端中测试它不会输出任何东西ok,但另一方面,使用 EUnit 测试它似乎返回{ok, value}

4

1 回答 1

3

实际上代码看起来不错。reverse/1也许您在util.erl尝试返回时还有其他功能{ok, Value}。尝试在没有util:指示的情况下更新您的测试:

%% -----------------------------------------------------------------------------
%% Tests the reverse list functionality.
%% -----------------------------------------------------------------------------
reverse_test_() -> [
  {"Reverse empty list", ?_test(begin

    % Reverse empty list.
    ?assertEqual([], reverse([]))
  end)},
  {"Reverse non-empty list", ?_test(begin

    % Reverse non-empty list.
    ?assertEqual([5, 4, 3, 2, 1], reverse([1, 2, 3, 4, 5]))
  end)}
].
于 2020-02-01T21:52:08.463 回答