模拟范围(L,N)
问题描述:
一大早使用Erlang打我得到一个奇怪的结果:模拟范围(L,N)
-module(bucle01).
-compile(export_all).
for(N) when N >=0 ->
lists:seq(1,N).
for(L,N) when L =< N ->
lists:seq(L,N);
for(L,N) when L > N ->
lists:reverse(for(N,L)).
当我运行程序我看到这一点:
> bucle01:for(1,10).
[1,2,3,4,5,6,7,8,9,10]
> bucle01:for(10,1).
[10,9,8,7,6,5,4,3,2,1]
>bucle01:for(7,10).
[7,8,9,10]
>bucle01:for(8,10).
"\b\t\n" %% What's that !?!
>bucle01:for(10,8).
"\n\t\b" %% After all it has some logic !
任何“库尔 - 援助“改为”不要喝太多“?
答
Erlang中的字符串只是ASCII数字的列表。 Erlang shell尝试在没有元数据的情况下通过查找可打印字符来确定您的列表是否是数字或字符串列表。
\b
(backspace),\t
(tab)和\n
(换行符)都是一些常见的ASCII字符,因此shell向您显示字符串而不是数字。但是,列表的内部结构完全相同。
这也涵盖了二郎FAQ: Why do lists of numbers get printed incorrectly?
而这里的一些想法,以防止这种神奇:Can I disable printing lists of small integers as strings in Erlang shell?
好的,谢谢,我现在只增加了下一行: – user1694815
-module(bucle01)。编译(export_all)。 -spec用于(L :: integer,N :: integer) - >整数。 – user1694815
现在看起来很好。 – user1694815