Erlang没有循环,怎么打三角形

Posted by Elton's Blog on November 13, 2012

大家都习惯用for循环打三角形,而Erlang恰恰没有for循环,看看如何使用Erlang打印三角呢?

43> [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))].
*********************
 *******************
  *****************
   ***************
    *************
     ***********
      *********
       *******
        *****
         ***
          *
[ok,ok,ok,ok,ok,ok,ok,ok,ok,ok,ok]
44> [begin L=lists:duplicate(2*X-1,"*"),S=lists:duplicate(11-X," "),io:format(S++L++"~n") end|| X<-lists:seq(1,11)].
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
*********************
[ok,ok,ok,ok,ok,ok,ok,ok,ok,ok,ok]

是不是更简单呢?

如果是简单的计数循环,更简单,例如:

52> [io:format("abc") || _<-lists:seq(1,10)]. 
abcabcabcabcabcabcabcabcabcabc[ok,ok,ok,ok,ok,ok,ok,ok,ok,ok]