简体   繁体   中英

Scala Fold operation using a Tuple

val g = List(1,2,3)

val k = g.fold((0,0))((a:Tuple2[Int,Int],b:Int)=>(a._1+b,a._2+1))

But i get the below error =

found   : ((Int, Int), Int) => (Int, Int)
 required: (Any, Any) => Any
              g.fold((0,0))((a:Tuple2[Int,Int],b:Int)=>(a._1+b,a._2+1))

Can someone please explain ,why its expecting a "Any" Type.

But below worked:

g.map((_,1))

g.map((_,1)).fold((0,0))((a,b)=> (a._1+b._1,a._2+b._2))
res211: (Int, Int) = (6,3)

It looks like you mean to use foldLeft :

val k = g.foldLeft((0,0))((a:Tuple2[Int,Int],b:Int)=>(a._1+b,a._2+1))

fold has the signature

def fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1 

so it requires the element type to match the accumulator type, while your example has different types for both.

To answer specifically this part:

Can someone please explain ,why its expecting a "Any" Type.

Lee's answer gives the signature: fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1 . In your case the compiler knows A is Int , and you pass (0,0) , which has type (Int, Int) , as z . So A1 has to be a supertype of both Int and (Int, Int) . Any is their least upper bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM