Skip to content

Instantly share code, notes, and snippets.

@yoshihiro503
Created July 2, 2012 09:14
Show Gist options
  • Save yoshihiro503/3032192 to your computer and use it in GitHub Desktop.
Save yoshihiro503/3032192 to your computer and use it in GitHub Desktop.
コップ本の3.6節の例題の別解を考えてみた。 https://twitter.com/yoshihiro503/status/219719644041318400
import scala.io.Source
def widthOfLength(s: String) = s.length.toString.length
def format(maxWidth : Int, line : String) = {
val padding = " " * (maxWidth - widthOfLength(line))
padding + line.length + " | " + line
}
def formatLines(lines : List[String]) : List[String] = {
if (lines.isEmpty) {
List()
} else {
val maxWidth = lines.map(widthOfLength).reduce(_ max _)
lines.map(format(maxWidth, _))
}
}
if (args.length > 0) {
val lines = Source.fromFile(args(0)).getLines().toList
formatLines(lines).foreach {(line) =>
println(line)
}
} else {
Console.err.println("ファイル名を指定してね")
}
@yoshihiro503
Copy link
Author

@yoshihiro503
Copy link
Author

ランダムテストもしてみた。
https://gist.github.com/3038807

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment