2016-05-11 12 views
0

Ich habe eine Funktion, die classTag verwendet, anstatt explizit den Datentyp eines Eingabeparameters zu definieren.classTag scala mit map

Zum Beispiel

def getColMult[T: ClassTag](A: Array[T], cols: Array[Int]): Array[Array[Double]] = { 
    if (cols.size == 1) { 
     var C = Array.apply(A.map{_(cols(0))}) 
     C.transpose 
     } 
    else { 
     var C = Array.apply(A.map{_(cols(0))},A.map{_(cols(1))}) 
     for (i <- (2 to cols.size - 1)) { 
      C = C++ Array(A.map{_(cols(i))}) 
     } 
     C.transpose 
    } 
} 

auf die Funktion ausgeführt wird, dies würde diesen Fehler:

Name: Kompilierfehler Nachricht:: 35: Fehler: T Parameter var C nicht statt = Array.apply (A.map (_ (cols (0))})

Konsole: 39: Fehler:. T nehmen keine Parameter var C = Array.apply (A.map {(cols (0))}, A.map { (cols (1))})

+0

Was versuchen Sie mit dieser Linie zu tun? –

+0

Ich versuche, eine bestimmte Spalte von einem Array [Array [Double]] zu erhalten A. Wenn ich nur eine Spalte abrufen muss, verwende ich diese Zeile A.map {_ (cols (0))} Ausgabe eines Arrays von Double entsprechend dieser Spalte. Um es als array Array zu machen, muss ich die apply-Funktion in scala verwenden. Wenn ich mehrere Spalten haben soll, muss ich Schleifen verwenden. –

+0

Aber 'T' ist nicht unbedingt ein' Array'. Der Compiler weiß also, dass das '_' in' A.map (...) 'alles sein kann. –

Antwort

1

Wenn Sie ersetzen _() mit _.apply(), wird der Fehler deutlicher:

import scala.reflect.ClassTag 

object Foo { 
    def getColMult[T: ClassTag](a: Array[T], cols: Array[Int]): Array[Array[Double]] = { 
    if (cols.size == 1) { 
     val c = Array(a.map({_.apply(cols(0))})) 
     c.transpose 
    } else { 
     val c = Array(a.map({_.apply(cols(0))}), a.map({_.apply(cols(1))})) ++ 
     (2 to cols.size - 1).flatMap({ i => 
      Array(a.map({_.apply(cols(i))})) 
     }) 
     c.transpose 
    } 
    } 
} 

Gibt Ihnen

test.scala:6: error: value apply is not a member of type parameter T 
     val c = Array(a.map({_.apply(cols(0))})) 
          ^
test.scala:9: error: value apply is not a member of type parameter T 
     val c = Array(a.map({_.apply(cols(0))}), a.map({_.apply(cols(1))})) ++ 
          ^
test.scala:9: error: value apply is not a member of type parameter T 
     val c = Array(a.map({_.apply(cols(0))}), a.map({_.apply(cols(1))})) ++ 
                 ^
test.scala:11: error: value apply is not a member of type parameter T 
      Array(a.map({_.apply(cols(i))})) 

Btw, dass Code sieht funktional äquivalent zu

def getColMult2[T: ClassTag](a: Array[T], cols: Array[Int]): Array[Array[Double]] = { 
    val c = cols.map({col => a.map({_.apply(col)})}) 
    c.transpose 
} 
Verwandte Themen