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 | }
13 comments:
Two heads are better than one. ............................................................
faith will move mountains. ..................................................
要保持更新呦,加油!!!期待你的新文章!!!.................................................................
知識可以傳授,智慧卻不行。每個人必須成為他自己。......................................................................
知識可以傳授,智慧卻不行。每個人必須成為他自己。.................................................................
成熟,就是有能力適應生活中的模糊。.................................................................
當一個人內心能容納兩樣相互衝突的東西,這個人便開始變得有價值了。............................................................
去冬眠以前,臨去秋波一下~~大家順利!!!............................................................
人生之中,比冒險更危險的一件事:不去冒險。..................................................
Readiness is all.............................................................
我們能互相給予的最佳禮物是「真心的關懷」。..................................................
很喜歡你的部落格,來給你加油,幫你推一下喔~期待你的下一個更新,謝謝............................................................
耐心是一株很苦的植物,但果實卻很甜美。..................................................
Post a Comment