Đây là loại điều mà shapeless có thể làm trong một generic cách, liên quan đến chuyển đổi thành một HList
.
Đầu tiên - get shapeless. Sau đó chạy scala với các loại phương pháp phụ thuộc bật (theo mặc định trong 2.10):
C:\Scala\sdk\scala-2.9.2\bin>scala -Ydependent-method-types
Welcome to Scala version 2.9.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_04).
Type in expressions to have them evaluated.
Type :help for more information.
Thêm hình thù vào classpath:
scala> :cp C:\Users\cmarsha\Downloads\shapeless_2.9.2-1.2.2.jar
Added 'C:\Users\cmarsha\Downloads\shapeless_2.9.2-1.2.2.jar'. Your new classpath is:
"C:\tibco\tibrv\8.2\lib\tibrvnative.jar;C:\Users\cmarsha\Downloads\shapeless_2.9.2-1.2.2.jar"
Bây giờ chúng ta chơi!
scala> (1, 2.3, 'a, 'b', "c", true)
res0: (Int, Double, Symbol, Char, java.lang.String, Boolean) = (1,2.3,'a,b,c,true)
Chúng ta phải nhập khẩu hình thù
scala> import shapeless._; import Tuples._; import Nat._
import shapeless._
import Tuples._
import Nat._
Chúng tôi lần lượt tuple của chúng tôi vào một HList
scala> res0.hlisted
res2: shapeless.::[Int,shapeless.::[Double,shapeless.::[Symbol,shapeless.::[Char,shapeless.::[java.lang.String,shapeless.::[Boolean,shapeless.HNil]]]]]] = 1 :: 2.3 :: 'a :: b :: c :: true :: HNil
Sau đó, chúng ta hãy là người đầu tiên 4 (lưu ý rằng _4
là một tham số kiểu, không phải là một đối số phương thức)
scala> res2.take[_4]
res4: shapeless.::[Int,shapeless.::[Double,shapeless.::[Symbol,shapeless.::[Char, shapeless.HNil]]]] = 1 :: 2.3 :: 'a :: b :: HNil
Bây giờ chuyển đổi trở lại một tuple
scala> res4.tupled
res5: (Int, Double, Symbol, Char) = (1,2.3,'a,b)
Chúng ta có thể rút ngắn này:
val (a, b, c, d) = sixtuple.hlisted.take[_4].tupled
//a, b, c and d would all have the correct inferred type
Điều này tất nhiên khái quát đến M
yếu tố đầu tiên của một N
-tuple
Tôi nghĩ rằng điều này có thể được thực hiện với [shapeless] (https://github.com/milessabin/shapeless) 'HList'. Hãy xem [câu hỏi này] (http://stackoverflow.com/questions/9028459/a-clean-way-to-combine-two-tuples-into-a-new-larger-tuple-in-scala). – incrop