Initializing a 2D (multi-dimensional) array in Scala

后端 未结 6 1453
深忆病人
深忆病人 2020-12-24 02:13

It\'s easy to initialize a 2D array (or, in fact, any multidimensional array) in Java by putting something like that:

int[][] x = new int[][] {
        { 3,          


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 02:42

    I suggest to use Scala 2.10 and macros:

    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 => _, _ }
    
        val matrix = Try {
          c.prefix.tree match {
            case Apply(_, List(Apply(_, List(Literal(Constant(raw: String)))))) =>
    
              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 => Literal(Constant(i)))) map (i => toArrayAST(i.toList))
    
              toArrayAST(matrixAST.toList)
          }
        }
    
        c.Expr(matrix getOrElse c.abort(c.enclosingPosition, "not a matrix of Int"))
      }
    
    }
    

    Usage with:

    scala> import MatrixMacro._
    import MatrixMacro._
    
    scala> matrix"1"
    res86: Array[Array[Int]] = Array(Array(1))
    
    scala> matrix"1,2,3"
    res87: Array[Array[Int]] = Array(Array(1, 2, 3))
    
    scala> 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> matrix"""
         |   1, 2
         |   1
         | """
    :57: error: rows of matrix do not have the same length
    matrix"""
    ^
    
    scala> matrix"a"
    :57: error: not a matrix of Int
                  matrix"a"
                  ^
    

    I don't think you will get it shorter. ;)

提交回复
热议问题