【问题标题】:Implementing drop function in Erlang在 Erlang 中实现 drop 函数
【发布时间】:2023-03-08 09:35:01
【问题描述】:

我正在尝试在 Erlang 中实现 drop 功能:
返回列表中除前 n 个项目之外的所有项目的集合。

step(N, C) ->
[_ | T] = C,
case (N > 0) and (length(C) > 0) of
  true ->
    step(N - 1, T);
  false ->
    C
end.


drop(_, [ ]) ->
  [ ];


drop(Number, Collection) ->
   step(Number, Collection).

在 Erlang 终端中:

 drop(3, [11, 22, 33, 44, 55, 66, 77]).
 "7BM"

任何想法为什么我得到那个输出?

请随意提出更惯用的 Erlang 方法。

【问题讨论】:

标签: algorithm erlang


【解决方案1】:

erlang 中的字符串是整数列表,如果所有这些值都在 ASCII 范围内,则 repl 将列表显示为字符串。请注意,您的 drop 实现似乎正在从输入列表中删除 n + 1 个元素,因为 drop(3, [11, 22, 33, 44, 55, 66, 77]) 应该是 [44, 55, 66, 77]

【讨论】:

  • 哦,如何将结果列表保存为整数?我要返回 [44, 55, 66, 77]
  • 我更正了布尔条件。感谢您的提示。
  • @Chiron - 结果仍然是整数列表,只是 repl 以这种方式格式化它们。如果您想查看基础值,您可以执行io:format("~w", drop(3, [11, 22, 33, 44, 55, 66, 77]))
【解决方案2】:
-module(wy).
-compile(export_all).


drop(_, []) ->
     [];
drop(0, Collection) ->
    Collection;
drop(Number, [_H | T]) ->
    drop(Number - 1, T).


main() ->
    L =  [11, 22, 33, 44, 55, 66, 77],
    io:format("~w~n", [drop(3, L)]).

输出是: [44,55,66,77]

w

Writes data with the standard syntax. This is used to output Erlang terms. Atoms are printed within quotes if they contain embedded non-printable characters, and floats are printed accurately as the shortest, correctly rounded string.

p

Writes the data with standard syntax in the same way as ~w, but breaks terms whose printed representation is longer than one line into many lines and indents each line sensibly. It also tries to detect lists of printable characters and to output these as strings. The Unicode translation modifier is used for determining what characters are printable.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 1970-01-01
    • 2013-12-08
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多