How to format a flat string with integers in it in erlang?

孤街醉人 提交于 2021-01-26 23:00:32

问题


In erlang, I want to format a string with integers in it and I want the result to be flattened. But I get this:

io_lib:format("sdfsdf ~B", [12312]).                 
[115,100,102,115,100,102,32,"12312"]

I can get the desired result by using the code below but it is really not elegant.

lists:flatten(io_lib:format("sdfsdf ~B", [12312])).
"sdfsdf 12312"

Is there a better formatting strings with integers in them, so that they are flat? Ideally, using only one function?


回答1:


You flatten a list using lists:flatten/1 as you've done in your example.

If you can accept a binary, list_to_binary/1 is quite efficient:

1> list_to_binary(io_lib:format("sdfsdf ~B", [12312])).
<<"sdfsdf 12312">>

However, question why you need a flat list in the first place. If it is just cosmetics, you don't need it. io:format/1,2,3 and most other port functions (gen_tcp etc) accept so called deep IO lists (nested lists with characters and binaries):

2> io:format([115,100,102,115,100,102,32,"12312"]).
sdfsdf 12312ok



回答2:


There is an efficiency reason that io_lib:format returns deep lists. Basically it saves a call to lists:flatten.

Ask yourself why you want the list flattened. If you are going to print the list or send it to a port or write it to a file, all those operations handle deep lists.

If you really need a flattened list for some reason, then just flatten it. Or you can create your own my_io_lib:format that returns flattened lists if you think it important.

(If you only want to flatten the list for debugging reasons then either print your strings with ~s, or create a flattener in an erlang module named user_default. Something like this:

 -module(user_default).
 -compile(export_all).
 %% either this:
 fl(String) ->
    lists:flatten(String).
 %% or this:
 pp(String) ->
     io:format("~s~n", [String]).

Then you can use fl/1 and print/1 in the Erlang shell (as long as user_default.beam is in your path of course).)



来源:https://stackoverflow.com/questions/6503289/how-to-format-a-flat-string-with-integers-in-it-in-erlang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!