在 Erlang 中从列表生成字符串

发布于 2024-10-02 16:53:36 字数 167 浏览 2 评论 0原文

我正在尝试根据列表生成格式化字符串:

[{"Max", 18}, {"Peter", 25}]

到字符串:

"(Name: Max, Age: 18), (Name: Peter, Age: 35)"

I'm trying to generate a formatted string based on a list:

[{"Max", 18}, {"Peter", 25}]

To a string:

"(Name: Max, Age: 18), (Name: Peter, Age: 35)"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦忆晨望 2024-10-09 16:53:36

第一步是创建一个可以将 {Name, Age} 元组转换为列表的函数:

format_person({Name, Age}) ->
    lists:flatten(io_lib:format("(Name: ~s, Age: ~b)", [Name, Age])).

下一部分只是将此函数应用于列表中的每个元素,然后将其连接在一起。

format_people(People) ->
    string:join(lists:map(fun format_person/1, People), ", ").

扁平化的原因是 io_lib 返回一个 iolist 而不是扁平列表。

The first step is to make a function that can convert your {Name, Age} tuple to a list:

format_person({Name, Age}) ->
    lists:flatten(io_lib:format("(Name: ~s, Age: ~b)", [Name, Age])).

The next part is simply to apply this function to each element in the list, and then join it together.

format_people(People) ->
    string:join(lists:map(fun format_person/1, People), ", ").

The reason for the flatten is that io_lib returns an iolist and not a flat list.

椒妓 2024-10-09 16:53:36

如果性能很重要,您可以使用此解决方案:

format([]) -> [];
format(List) ->
  [[_|F]|R] = [ [", ","(Name: ",Name,", Age: ",integer_to_list(Age)|")"]
              || {Name, Age} <- List ],
  [F|R].

但请记住,它返回 io_list(),因此如果您想查看结果,请使用 lists:flatten/1。这是如何在 Erlang 中编写非常高效的字符串操作的方法,但仅当性能远比可读性和可维护性重要时才使用它。

If performance is important, you can use this solution:

format([]) -> [];
format(List) ->
  [[_|F]|R] = [ [", ","(Name: ",Name,", Age: ",integer_to_list(Age)|")"]
              || {Name, Age} <- List ],
  [F|R].

But remember that it returns io_list() so if you want see result, use lists:flatten/1. It is way how to write very efficient string manipulations in Erlang but use it only if performance is far more important than readability and maintainability.

情深缘浅 2024-10-09 16:53:36

一个简单但缓慢的方法:

string:join([lists:flatten(io_lib:format("(~s: ~p)", [Key, Value])) || {Key,Value} <- [{"Max", 18}, {"Peter", 25}]], ", ").

A simple but slow way:

string:join([lists:flatten(io_lib:format("(~s: ~p)", [Key, Value])) || {Key,Value} <- [{"Max", 18}, {"Peter", 25}]], ", ").
巨坚强 2024-10-09 16:53:36

是 JSON 吗?

使用一些已经编写的模块,例如 mochiweb。

is it JSON?

use some already written modules in e.g mochiweb.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文