| 
    
        |  | Re: Last example in chapter 3 issues.. | Posted: Aug 24, 2008 9:33 PM |  |  
        | Hi Alan, 
 Here's how I'd avoid calculating widthOfLength twice:
 
 
 import scala.io.Source
 
 def widthOfLength(s: String) = s.length.toString.length
 
 if (args.length > 0) {
 val lines = Source.fromFile(args(0)).getLines.toList
 val widths = lines.map(widthOfLength)
 val maxWidth = widths.reduceLeft((a, b) => a.max(b))
 val zipped = lines zip widths
 for ((line, widthOfLength) <- zipped) {
 val numSpaces = maxWidth - widthOfLength
 val padding = " " * numSpaces
 print(padding + line.length +" | "+ line)
 }
 }
 else
 Console.err.println("Please enter filename")
 
 
 You can zip the widths list together with the lines list, then use a pattern in the for expression to pull them apart. The reason I didn't do something like that in the book was that we hadn't explained patterns yet. We try very hard to show each new thing based on things that came before, and just introduce one new idea at a time, where possible.
 
 The other thing to consider, though, is that although I've reduced by half the number of times I calculate the width of length of each line here, I've at the same time increased the memory used by the script, because I have added the zipped list. I'd doubt there would be any perceptible difference between the performance of either script for most files.
 
         |  |