Monday, March 3, 2008

2 or more, use a for

I want to start this post with a citation. Dijkstra coined the phrase "2 or more, use a for". In common use a for loop is an abstraction for iterating through a collection.

In scalax the for keyword is used to build something like the "using" keyword in C#. As expected the following code to copy a file line by line contains three nested iterations:
def createReader = ManagedResource(new BufferedReader(new FileReader("test.txt")))
def createWriter = ManagedResource(new BufferedWriter(new FileWriter("test_copy.txt")))

//copy a file, line by line
for(reader <- createReader; writer <- createWriter) {
var line = reader.readLine
while (line != null) {
writer.write(line)
writer.newLine
line = reader.readLine
}
}

You can find more on how to build an Automatic Ressource Management feature for Scala on Chris Hansen's Blog: Polyglot Window: Chris Hansen's Blog: ARM Blocks in Scala, Part 3: The Concession

No comments: