Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I suggest to use Scala 2.10 and macros:</p> <pre><code>object MatrixMacro { import language.experimental.macros import scala.reflect.macros.Context import scala.util.Try implicit class MatrixContext(sc: StringContext) { def matrix(): Array[Array[Int]] = macro matrixImpl } def matrixImpl(c: Context)(): c.Expr[Array[Array[Int]]] = { import c.universe.{ Try =&gt; _, _ } val matrix = Try { c.prefix.tree match { case Apply(_, List(Apply(_, List(Literal(Constant(raw: String)))))) =&gt; def toArrayAST(c: List[TermTree]) = Apply(Select(Select(Ident("scala"), newTermName("Array")), newTermName("apply")), c) val matrix = raw split "\n" map (_.trim) filter (_.nonEmpty) map { _ split "," map (_.trim.toInt) } if (matrix.map(_.length).distinct.size != 1) c.abort(c.enclosingPosition, "rows of matrix do not have the same length") val matrixAST = matrix map (_ map (i =&gt; Literal(Constant(i)))) map (i =&gt; toArrayAST(i.toList)) toArrayAST(matrixAST.toList) } } c.Expr(matrix getOrElse c.abort(c.enclosingPosition, "not a matrix of Int")) } } </code></pre> <p>Usage with:</p> <pre><code>scala&gt; import MatrixMacro._ import MatrixMacro._ scala&gt; matrix"1" res86: Array[Array[Int]] = Array(Array(1)) scala&gt; matrix"1,2,3" res87: Array[Array[Int]] = Array(Array(1, 2, 3)) scala&gt; matrix""" | 1, 2, 3 | 4, 5, 6 | 7, 8, 9 | """ res88: Array[Array[Int]] = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9)) scala&gt; matrix""" | 1, 2 | 1 | """ &lt;console&gt;:57: error: rows of matrix do not have the same length matrix""" ^ scala&gt; matrix"a" &lt;console&gt;:57: error: not a matrix of Int matrix"a" ^ </code></pre> <p>I don't think you will get it shorter. ;)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload