title: Matrix to CSV in Scala
body: <p>Writing an MxN matrix ( M rows, N columns ) to a CSV file:</p>
  
  <p>My first attempt, using map, works, but creates N references to the stringbuffer. It also writes an unnecessary comma at the end of each row.</p>
  
  <pre><code>def matrix2csv(matrix:List[List[Double]], filename: String ) = {
    val pw = new PrintWriter( filename )
    val COMMA = ","
  
    matrix.map( row =&gt; {
      val sbuf = new StringBuffer  
      row.map( elt =&gt; sbuf.append( elt ).append( COMMA ))
      pw.println(sbuf)
    })
    pw.flush
    pw.close
  }
  </code></pre>
  
  <p>My second attempt, using reduce, also works but looks clunky:</p>
  
  <pre><code>def matrix2csv(matrix:List[List[Double]], filename: String ) = {
    val pw = new PrintWriter( filename )
    val COMMA = ","
  
    matrix.map( row =&gt; {
      val sbuf = new StringBuffer  
      val last = row.reduce( (a,b)=&gt; {
        sbuf.append(a).append(COMMA)
        b
      })
      sbuf.append(last)
      pw.println(sbuf)
    })
    pw.flush
    pw.close
  }
  </code></pre>
  
  <p>Any suggestions on a more concise and idiomatic approach ? Thanks.</p>