這裏是我的投籃吧。我用escript因此它可以在命令行中運行,但它可以很容易地放入模塊:
#!/usr/bin/env escript
main(_Args) ->
% Read a line from stdin, strip dos&unix newlines
% This can also be done with io:get_line/2 using the atom 'standard_io' as the
% first argument.
Line = io:get_line("Enter num:"),
LineWithoutNL = string:strip(string:strip(Line, both, 13), both, 10),
% Try to transform the string read into an unsigned int
{ok, [Num], _} = io_lib:fread("~u", LineWithoutNL),
% Using a list comprehension we can print the string for each one of the
% elements generated in a sequence, that goes from 1 to Num.
[ io:format("Hello world!~n") || _ <- lists:seq(1, Num) ].
如果你不想使用列表理解,這是一個類似的方法到最後通過使用列表:foreach和相同的序列:
% Create a sequence, from 1 to Num, and call a fun to write to stdout
% for each one of the items in the sequence.
lists:foreach(
fun(_Iteration) ->
io:format("Hello world!~n")
end,
lists:seq(1,Num)
).
+1尾遞歸! – marcelog