Friday, June 4, 2010

Formatting Console Output in Scala

So it's midnight and I'm programming Scala (heh).  I'm actually starting to be able to write little scripts in Scala.  Here's a quick one that I put together, inspired by Chapter 3 of "Programming Scala" which reads a source code file and formats the file to the screen with line numbers.



I tried to be as functional as possible.  The "formatSourceLine" I felt was getting close to the concept, using recursion, immutable values, and always returning a value (avoiding the side effect of printing from within the function).

The actual output from this script is:

D:\Development\Scala>scala file.scala file.scala

    1 | import scala.io.Source
    2 |
    3 | if (args.length > 0) {
    4 |
    5 |     def formatSourcePrefix(line: Int, suffix: String, max: Int = 5):
    6 |         var prefix: String = ""
    7 |         for (i <- 1 to (max - line.toString.length))
    8 |             prefix += " "
    9 |         prefix + line.toString + suffix
   10 |     }
   11 |
   12 |     def formatSourceLine(lines: List[String], line: Int = 1, 
   13 |         val out = output + formatSourcePrefix(line, " | ")
   14 |         if (lines.length > 1)
   15 |             formatSourceLine(lines.tail, line + 1, out)
   16 |         else
   17 |             out
   18 |     }
   19 |
   20 |     // Read file from disk
   21 |     val lines = Source.fromPath(args(0)).getLines().toList
   22 |
   23 |     // Print results to screen
   24 |     println
   25 |     print(formatSourceLine(lines))
   26 |
   27 | }
   28 | else {
   29 |     // Print out proper syntax
   30 |     Console.err.println
   31 |     Console.err.println("scala file.scala [filename]")
   32 | }

  © Blogger template 'Minimalist G' by Ourblogtemplates.com 2008

Back to TOP