Writing the MxN matrix (M rows, N columns) in a CSV file:
My first attempt using a map works, but it creates N references to stringbuffer. He also writes an unnecessary comma at the end of each line.
def matrix2csv(matrix:List[List[Double]], filename: String ) = {
val pw = new PrintWriter( filename )
val COMMA = ","
matrix.map( row => {
val sbuf = new StringBuffer
row.map( elt => sbuf.append( elt ).append( COMMA ))
pw.println(sbuf)
})
pw.flush
pw.close
}
My second attempt using shorthand also works, but it looks awkward:
def matrix2csv(matrix:List[List[Double]], filename: String ) = {
val pw = new PrintWriter( filename )
val COMMA = ","
matrix.map( row => {
val sbuf = new StringBuffer
val last = row.reduce( (a,b)=> {
sbuf.append(a).append(COMMA)
b
})
sbuf.append(last)
pw.println(sbuf)
})
pw.flush
pw.close
}
Any suggestions for a more concise and idiomatic approach? Thank.
source
share