shapeless支持映射和經由中間HList
表示摺疊元組,
樣品REPL會話,
scala> import shapeless._ ; import Tuples._
import shapeless._
import Tuples._
scala> object double extends (Int -> Int) (_*2)
defined module double
scala> (3, 4).hlisted.map(double).tupled
res0: (Int, Int) = (6,8)
當數組的元素是不同的類型,您可以與特定類型的情況下,多態函數映射的,
scala> object frob extends Poly1 {
| implicit def caseInt = at[Int](_*2)
| implicit def caseString = at[String]("!"+_+"!")
| implicit def caseBoolean = at[Boolean](!_)
| }
defined module frob
scala> (23, "foo", false, "bar", 13).hlisted.map(frob).tupled
res1: (Int, String, Boolean, String, Int) = (46,!foo!,true,!bar!,26)
更新
至於無形2.0.0-M1映射在元組的直接支持。上面的例子現在看起來像這樣,
scala> import shapeless._, poly._, syntax.std.tuple._
import shapeless._
import poly._
import syntax.std.tuple._
scala> object double extends (Int -> Int) (_*2)
defined module double
scala> (3, 4) map double
res0: (Int, Int) = (6,8)
scala> object frob extends Poly1 {
| implicit def caseInt = at[Int](_*2)
| implicit def caseString = at[String]("!"+_+"!")
| implicit def caseBoolean = at[Boolean](!_)
| }
defined module frob
scala> (23, "foo", false, "bar", 13) map frob
res1: (Int, String, Boolean, String, Int) = (46,!foo!,true,!bar!,26)
它看起來像你正在使用一個元組,你真的應該使用一個集合。考慮使用真正的集合類 - 元組不應該被用作一種集合。 – Jesper 2010-04-30 18:47:06
@Jesper:我不同意:我可能只是簡單地將DRY'ly應用於相同的操作,並精確地應用於大小靜態已知的項目集合。 – 2014-03-08 05:16:11