刚刚看到微博上有朋友说"哎~连个for循环都没有的erlang我真想不出该怎么去打印星号三角形了。。。",哈哈,一起来Happy一下吧,一起来打印三角形!!在Shell中打印出来的效果贴文本会有错位我就贴图了;
先来个简单的,首先想到的是使用string:right/2的格式化方法,本来是想省事的,实际上不用更简单,我的答案如下:
1> [begin L=lists:duplicate(X,"*"),io:format(string:right(L++"~n",X)) end|| X<-lists:seq(2,11)]. 2> [begin L=lists:duplicate(X,"*"),io:format(string:right(L++"~n",X)) end|| X<-lists:reverse(lists:seq(2,11))]. 3> [begin L=lists:duplicate(X,"*"),io:format(string:right(L++"~n",13-length(L)+X)) end|| X<-lists:reverse(lists:seq(1,11))]. 4> [begin L=lists:duplicate(X,"*"),S=lists:duplicate(11-X," "),io:format(S++L++"~n") end|| X<-lists:reverse(lists:seq(1,11))]. 5> [begin L=lists:duplicate(X,"*"),S=lists:duplicate(11-X," "),io:format(S++L++"~n") end|| X<-lists:seq(1,11)]. 6> [begin L=lists:duplicate(2*X-1,"*"),S=lists:duplicate(11-X," "),io:format(S++L++"~n") end|| X<-lists:reverse(lists:seq(1,11))]. 7> [begin L=lists:duplicate(2*X-1,"*"),S=lists:duplicate(11-X," "),io:format(S++L++"~n") end|| X<-lists:seq(1,11)].
是不是不用string:right/2更简单?
抛砖引玉了,你有更简单的方法么?
P.S 附赠一个九九乘法表打印
6> [begin L =lists:seq(1,9),lists:foreach(fun(N) -> io:format("~p X ~p = ~p; ",[N,X,N*X]) end ,L),io:format("~n") end || X<-lists:seq(1,9)]. 1 X 1 = 1; 2 X 1 = 2; 3 X 1 = 3; 4 X 1 = 4; 5 X 1 = 5; 6 X 1 = 6; 7 X 1 = 7; 8 X 1 = 8; 9 X 1 = 9; 1 X 2 = 2; 2 X 2 = 4; 3 X 2 = 6; 4 X 2 = 8; 5 X 2 = 10; 6 X 2 = 12; 7 X 2 = 14; 8 X 2 = 16; 9 X 2 = 18; 1 X 3 = 3; 2 X 3 = 6; 3 X 3 = 9; 4 X 3 = 12; 5 X 3 = 15; 6 X 3 = 18; 7 X 3 = 21; 8 X 3 = 24; 9 X 3 = 27; 1 X 4 = 4; 2 X 4 = 8; 3 X 4 = 12; 4 X 4 = 16; 5 X 4 = 20; 6 X 4 = 24; 7 X 4 = 28; 8 X 4 = 32; 9 X 4 = 36; 1 X 5 = 5; 2 X 5 = 10; 3 X 5 = 15; 4 X 5 = 20; 5 X 5 = 25; 6 X 5 = 30; 7 X 5 = 35; 8 X 5 = 40; 9 X 5 = 45; 1 X 6 = 6; 2 X 6 = 12; 3 X 6 = 18; 4 X 6 = 24; 5 X 6 = 30; 6 X 6 = 36; 7 X 6 = 42; 8 X 6 = 48; 9 X 6 = 54; 1 X 7 = 7; 2 X 7 = 14; 3 X 7 = 21; 4 X 7 = 28; 5 X 7 = 35; 6 X 7 = 42; 7 X 7 = 49; 8 X 7 = 56; 9 X 7 = 63; 1 X 8 = 8; 2 X 8 = 16; 3 X 8 = 24; 4 X 8 = 32; 5 X 8 = 40; 6 X 8 = 48; 7 X 8 = 56; 8 X 8 = 64; 9 X 8 = 72; 1 X 9 = 9; 2 X 9 = 18; 3 X 9 = 27; 4 X 9 = 36; 5 X 9 = 45; 6 X 9 = 54; 7 X 9 = 63; 8 X 9 = 72; 9 X 9 = 81;