Matrix for CSV in Scala

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.

+5
source share
2 answers

You can easily get a string representation:

val csvString = matrix.map{ _.mkString(", ") }.mkString("\n")

Then you just need to upload it to a file.

Pay attention to the final lines (here "\ n"), they vary depending on the platform.

+8
source

, map, . foreach.

, foreach StringBuffer mkString:

def matrix2csv(matrix:List[List[Double]], filename: String) {
  val pw = new PrintWriter(filename)
  val COMMA = ","
  matrix.foreach { row => pw.println(row mkString COMMA) }
  pw.flush
  pw.close
}

, mkString StringBuilder ( StringBuffer, ).

+5

All Articles