Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala foldLeft on Maps

How do you use Map.foldLeft? According to the docs it looks like

foldLeft [B] (z: B)(op: (B, (A, B)) ⇒ B) : B 

But I'm having difficulty:

Map("first"->1,"second"->2).foldLeft(0)((a,(k,v)) => a+v ) 

error: not a legal formal parameter

The error points to the open bracket in front of k.

like image 359
Pengin Avatar asked Nov 14 '10 17:11

Pengin


2 Answers

If you want to use the (a, (k, v)) syntax, you need to advise the compiler to use pattern matching.

Map("first"->1, "second"->2).foldLeft(0){ case (a, (k, v)) => a+v } 

Note that a case statement requires curly braces.

like image 52
Debilski Avatar answered Sep 29 '22 06:09

Debilski


I think, you can't do the pattern match on tuples as you expect:

Map("first"->1,"second"->2).foldLeft(0)((a, t) => a + t._2) 

Actually, using values and sum is simpler.

Map("first"->1,"second"->2).values.sum 
like image 28
Thomas Jung Avatar answered Sep 29 '22 06:09

Thomas Jung