Scala tuple与map
程序员文章站
2022-05-10 12:36:06
...
一 tuple
scala>(1,2)
res27:(Int,Int)=(1,2)
scala>(1->2)
res28:(Int,Int)=(1,2)
scala>(1,"Alice","Math",97.5)
res30:(Int,String,String,Double)=(1,Alice,Math,97.5)
scala> val t =(1,"Alice","Math",97.5)
t:(Int,String,String,Double)=(1,Alice,Math,97.5)
scala> t._1
res31:Int=1
scala> t._2
res32:String=Alice
scala> t._3
res33:String=Math
scala> t._4
res34:Double=97.5
scala> l
res35:List[Int]=List(1,2,3)
scala>def sumSq(in:List[Int]):(Int,Int,Int)=
|in.foldLeft((0,0,0))((t,v)=>(t._1+1,t._2+v,t._3+v*v))
sumSq:(in:List[Int])(Int,Int,Int)
scala> sumSq(l)
res36:(Int,Int,Int)=(3,6,14)
二 Map[K,V]
scala> val p =Map(1->"Davie",2->"Elwood")
p: scala.collection.immutable.Map[Int,String]=Map(1->Davie,2->Elwood)
scala> p(1)
res37:String=Davie
scala> p(2)
res38:String=Elwood
scala> p.contains(1)
res39:Boolean= true
scala> p.contains(3)
res40:Boolean= false
scala> p.keys
res41:Iterable[Int]=Set(1,2)
scala> p.values
res42:Iterable[String]=MapLike.DefaultValuesI