@puppies , over at StackOverflow, had a question about how to print a filled rectangle in Scala. I guess s/he has an imperative background, because a) we all do, and b) s/he made an attempt to do this using loops. But in Scala, you can also do this with mapping and list concatenation.
Here’s my initial take (all code is printed on the scala REPL):
val ec="@"
val cc="X"
val cols=8
val rows=5
((ec*(cols+2)) +: Range(0,rows).map( _ => ec+cc*cols+ec) :+ (ec*(cols+2)) ).foreach( println(_) )
Which results in
@@@@@@@@@@
@XXXXXXXX@
@XXXXXXXX@
@XXXXXXXX@
@XXXXXXXX@
@XXXXXXXX@
@@@@@@@@@@
So then, Ben Reich suggested using until
in stead of Range
. Also, we can replace the side-effect in foreach
with mkString
:
((ec*(cols+2)) +: (0 until rows).map( _ => ec+cc*cols+ec) :+ (ec*(cols+2)) ).mkString("\n")
Can you print this rectangle using a shorter snippet? Post your version in the comments.
This would also work:
(ec*(cols+2)+"\n") + (ec+cc*cols+ec+"\n")*rows + (ec*(cols+2))